结合正则表达式,匹配两者,而不是

时间:2016-05-10 09:24:13

标签: javascript regex

好的,我想要结合两个正则表达式。在下面的示例中,我想提取任何只包含指定字母的单词,然后是该列表中的单词,在本例中只提取另一个字母r。

我在这个论坛上看过几篇文章。

例如一个是: Combining regular expressions in 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"]]

再次,谢谢。

1 个答案:

答案 0 :(得分:3)

仅匹配由T2reinterpret_castgdof字符组成的字符串以及{ {1}},使用

p

参见regex和JS演示:

&#13;
&#13;
r
&#13;
&#13;
&#13;