javascriptregexnode.jstrailsjs

Regex allow multiple work in a sentence


I'm trying to parse following sentences with regex (javascript) :

Currently I'm trying : I(\b[a-zA-Z]*\b){0,5}(TV|chocolate|fire) but it doesn't work. I also made some test with \w but no luck.

I want to allow any word (max 5 words) between "I" and the last word witch is predefined.


Solution

  • To account for non-word chars in-between words, you may use

    /I(?:\W+\w+){0,5}\‌​W+(?:TV|chocolate|fir‌​e)/
    

    See the regex demo

    The point is that you added word boundaries, but did not account for spaces, punctuation, etc. (all the other non-word chars) between "words".

    Pattern details: