jaumard jaumard - 3 months ago 7
Node.js Question

Regex allow multiple work in a sentence

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


  • I wish a TV

  • I want some chocolate

  • I need fire



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.

Answer

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:

  • I - matches the left delimiter
  • (?:\W+\w+){0,5}\‌​W+ - matches 0 to 5 sequences (due to the limiting quantifier {n,m}) of 1+ non-word chars (\W+) and 1+ word chars after them (\w+), and a \W+ at the end matches 1 or more non-word chars that must be present to separate the last matched word chars from the...
  • (?:TV|chocolate|fir‌​e) - matches the trailing delimiter