jaumard jaumard - 1 year ago 77
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 :
but it doesn't work. I also made some test with
but no luck.

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

Answer Source

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download