After reading how to write a regexp in Javascript, I'm still pretty confused how to write this one...
I want to match every string containing at least one occurence of 2 substrings, in any order.
Say sub1 = "foo" and sub2 = "bar"
foo => doesn't match
bar => doesn't match
foobar => matches
barfoo => matches
foohellobar => matches
Could somebody help me with this ?
Additionnally, I'd like to exclude another substring. So it would match the strings containing the 2 substrings like before, but not containing a sub3, regardless of its order with the 2 others.
Thanks a lot
This will work:
/.*foo.*bar|.*bar.*foo/g
.*
matches 0 or many characters (where .
matches any character and *
stands for 0 or many)
|
is regex' or operator
Generated code from regex101:
var re = /.*foo.*bar|.*bar.*foo/g; var str = 'foobar'; var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
That being said, better use Oriol's answer using indexOf()
or includes()
.
I would not use a complicated regex, but instead just used logical operand &&
.
var param = 'foobar'; alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/)); param = 'foobarzoo'; alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/));
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.