好的,我想要结合两个正则表达式。在下面的示例中,我想提取任何只包含指定字母的单词,然后是该列表中的单词,在本例中只提取另一个字母r。
我在这个论坛上看过几篇文章。
例如一个是: Combining regular expressions in Javascript
他们说要将表达式与|
,exp1|exp2
结合起来。这就是我所做的,但我得到的话我不应该。如何在下面的示例中合并r1
和r2
?
感谢您的帮助。
//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"]]
再次,谢谢。
答案 0 :(得分:3)