RegExp.exec()偶尔返回NULL [英] RegExp.exec() returns NULL sporadically
问题描述
我对此非常认真,我已经花费了不成比例的时间来试图弄清楚这里发生了什么。所以请给我一个手=)
I am seriously going crazy over this and I've already spent an unproportionate amount of time on trying to figure out what's going on here. So please give me a hand =)
我需要在JavaScript中对字符串进行一些RegExp匹配。不幸的是,它表现得非常奇怪。此代码:
I need to do some RegExp matching of strings in JavaScript. Unfortunately it behaves very strangely. This code:
var rx = /(cat|dog)/gi;
var w = new Array("I have a cat and a dog too.", "There once was a dog and a cat.", "I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.");
for (var i in w) {
var m = null;
m = rx.exec(w[i]);
if(m){
document.writeln("<pre>" + i + "\nINPUT: " + w[i] + "\nMATCHES: " + m.slice(1) + "</pre>");
}else{
document.writeln("<pre>" + i + "\n'" + w[i] + "' FAILED.</pre>");
}
}
首先返回cat和dog两个元素,应该是,但是然后一些 exec()
-calls开始返回 null
。我不明白为什么。
Returns "cat" and "dog" for the first two elements, as it should be, but then some exec()
-calls start returning null
. I don't understand why.
我发了一个小提琴这里,您可以在其中运行和编辑代码。
I posted a Fiddle here, where you can run and edit the code.
到目前为止,我已经在Chrome和Firefox中尝试过此操作。
And so far I've tried this in Chrome and Firefox.
干杯!
/ Christofer
/Christofer
推荐答案
哦,就是这样。因为你正在定义你的正则表达式全局,它匹配第一个 cat
,并在循环的第二次传递 dog
。所以,基本上你只需要重置你的正则表达式(它的内部指针)。参看这个:
Oh, here it is. Because you're defining your regex global, it matches first cat
, and on the second pass of the loop dog
. So, basically you just need to reset your regex (it's internal pointer) as well. Cf. this:
var w = new Array("I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too.");
for (var i in w) {
var rx = /(cat|dog)/gi;
var m = null;
m = rx.exec(w[i]);
if(m){
document.writeln("<p>" + i + "<br/>INPUT: " + w[i] + "<br/>MATCHES: " + w[i].length + "</p>");
}else{
document.writeln("<p><b>" + i + "<br/>'" + w[i] + "' FAILED.</b><br/>" + w[i].length + "</p>");
}
document.writeln(m);
}
这篇关于RegExp.exec()偶尔返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!