组合regex,同时匹配两者,而不是两者都匹配

Combining regex, matching both, not either

本文关键字:两者都 regex 组合      更新时间:2023-09-26

好的,我想合并两个正则表达式。在下面的例子中,我想提取任何只指定了字母的单词,然后在该列表中,只提取另一个字母的单词。

我在这个论坛上读了几篇文章。

例如:Javascript 中正则表达式的组合

他们说要把这些表达式和|exp1|exp2结合起来。我就是这么做的,但我得到了不该说的话。如何在下面的示例中组合r1r2

谢谢你的帮助。

//the words in list form.
var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" "),
//doesn't work, can we fix?
     r = /^[gdofpr]+$|[r]+/,
    //These work.
    r1 = /^[gdofpr]+$/,
    r2 = /[r]+/,
    //save the matches in a list.
    badMatch = [], 
    goodMatch = [];
//loop through a.
for (var i = 0; i < a.length; i++) {
    //bad, doesn't get what I want.
    if (a[i].match(r)) badMatch[badMatch.length] = a[i];
    //works, clunky. Can we combine these?
    if (a[i].match(r1) && a[i].match(r2)) goodMatch[goodMatch.length] = a[i];
} //i
alert(JSON.stringify([badMatch, goodMatch])); //just to show what we got.

我得到以下内容。

[
    ["frog", "dog", "trig", "srig", "strog", "prog"],
    ["frog", "prog"]]

再次感谢。

要只匹配由gdofpr字符组成的字符串,并且这些字符串还具有r,请使用

/^[gdofpr]*r[gdofpr]*$/

请参阅regex和JS演示:

var a = "frog dog trig srig swig strog prog log smog snog fig pig pug".split(" ");
var res = a.filter(x => /^[gdofpr]*r[gdofpr]*$/.test(x));
document.body.innerHTML = JSON.stringify(res, 0, 4);