How do I ignore anything in between with Javascript RegEx?
For example, I want to detect all three words: how
are
you
in that order.
My regex:
var pattern = /([how]+[are]+[you]+)/i;
pattern.test("howare"); //false <--- expected (correct)
pattern.test("areyou"); //false <--- expected (correct)
pattern.test("howareyou"); //true <--- expected (correct)
pattern.test(" howareyou! "); //true <--- expected (correct)
pattern.test("how are you"); //false <--- this should match!
pattern.test("how areyou "); //false <--- this should match!
But then I want to ignore anything in between them.
You just want to add a wildcard in between your words by using
.* // 0 or more of any character
Regex rules are by default greedy, so trying to match are
will take precedence over .*
.
To note however you need to take out your square brackets as they'll currently allow things to match that shouldn't. For example they would allow hooooowareyou
to match, as the square brackets allow all of the given characters, and the +
indicates 1 or more.
Try something like:
how.*are.*you
It's unclear if you want all your test cases to pass, if you do then here's an example of this answer in action https://regex101.com/r/aTTU5b/2
You can use this regex:
how.*?are.*?you
This will ensure that how , are and you are present in the same order and ignore any characters in-between. So it will return a match for howwww areee!#%@!$%$#% you?
etc. Check out more positive and negative cases using the demo link below:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.