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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try this:
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!