Reputation: 1799
I try to write regular expression for Mongo DB query. I need to get all posts which title first 5 words contain "foo".
E.g.
"It is a foo day" //true
"I try to find word foo" //false
Now I have '/^((\w+\s+){,5})\bfoo/i'
but it does not work.
Upvotes: 1
Views: 218
Reputation: 2847
Try this:
/^(((\w+\s+){,4})foo)(?!\w)/i
I dropped the 5 to a 4 to only match the first 4 words along with their succeeding spaces. Since the spaces are then captured beforehand, the \b is unnecessary. Then find the foo. Afterward, we only want to match 'foo' and not 'foot' or 'food', so we make a negative lookahead for word characters.
Here's a site that shows cases that work: http://rubular.com/r/3TQiR3pvku
Hope this helps!
Upvotes: 1