Reputation: 1687
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
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
Reputation: 4805
Try this expression
'/^.\S+(\s){N}/'
Start with any character and match up to N words.
Upvotes: 0
Reputation: 16506
I guess you can achieve this without even regex:
str.split[0...n].join(' ')
Upvotes: 0