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.
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.
Share Improve this question edited May 4, 2017 at 14:06 Sebastian Proske 8,4232 gold badges29 silver badges38 bronze badges asked May 4, 2017 at 13:51 夏期劇場夏期劇場 18.4k46 gold badges141 silver badges226 bronze badges 2- 1 I'm sorry if you confused. Edited the question a bit now. – 夏期劇場 Commented May 4, 2017 at 13:58
- That does help clarify (though I'd assumed that was the case in my answer). – Ian Commented May 4, 2017 at 13:59
2 Answers
Reset to default 3You 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./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:
Demo: https://regex101./r/rzhkHC/3
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745041209a4607818.html
评论列表(0条)