Flezcano
Flezcano

Reputation: 1687

Regex for first x words in string

I need a regex that returns the first N words from a string, including line breaks and white spaces. I tried with the following code, but the server crashes:

str[/\S+(\s)?{N}/].strip

Upvotes: 0

Views: 1015

Answers (3)

zx81
zx81

Reputation: 41838

Like this (for the first 15 words):

if subject =~ /^(?:\w+\s){15}/
    thefirstwords = $&

Just change the 15 to whatever number you like.

Upvotes: 1

smali
smali

Reputation: 4805

Try this expression

'/^.\S+(\s){N}/'

Start with any character and match up to N words.

Upvotes: 0

shivam
shivam

Reputation: 16506

I guess you can achieve this without even regex:

str.split[0...n].join(' ')

Upvotes: 0

Related Questions