Javascript正则表达式:匹配任意顺序的2个子字符串

Javascript regular expression : match 2 substrings in any order

本文关键字:2个 字符串 顺序 任意 正则表达式 Javascript      更新时间:2023-09-26

在阅读了如何在Javascript中编写regexp之后,我仍然很困惑如何编写这个…

我要匹配包含至少一个两个子字符串的字符串,以任何顺序。

说sub1 = "foo"和sub2 = "bar"

foo =>不匹配

bar =>不匹配

foobar => matches

barfoo => matches

foohellobar => matches

有人能帮我一下吗?

另外,我想排除另一个子字符串。因此,它将像以前一样匹配包含两个子字符串的字符串,但不包含sub3,无论其与其他两个子字符串的顺序如何。

Thanks to lot

您可以使用indexOf:

str.indexOf(sub1) > -1 && str.indexOf(sub2) > -1

或ES6中的includes:

str.includes(sub1) && str.includes(sub2)

或者如果你有一个子字符串数组:

[sub1, sub2/*, ...*/].every(sub => str.includes(sub));

可以:

/.*foo.*bar|.*bar.*foo/g

.*匹配0或多个字符(其中.匹配任何字符,*表示0或多个字符)

| is regex' or operator

从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.
}

演示

话虽如此,最好使用Oriol的答案使用indexOf()includes()

我不会使用复杂的正则表达式,而只是使用逻辑操作数&&

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/));