Firefox 3.6.20 regex给出不一致的结果



我调试这个应用程序已经有一段时间了,它让我看到了这个测试用例。当我在firefox 3.6中运行它时。X,它只有50%的时间有效。

var success = 0;
var pat = /(d{2})/(d{2})/(d{4})s(d{2}):(d{2})s(am|pm)/g;
var date = "08/01/2011 12:00 am";
for(var i=0;i<100;i++) if(pat.exec(date)) success++;
alert("success: " + success + " failed: " + (100 - success));

它警告success: 50 failed: 50

这是怎么回事?

g标志表示,在第一次匹配之后,第二次搜索从匹配的子字符串的末尾开始(即在字符串的末尾),并且失败,将开始位置重置为字符串的开头。

如果正则表达式使用"g"标志,则可以多次使用exec方法在同一字符串中查找连续匹配。当您这样做时,搜索从正则表达式的lastIndex属性指定的str的子字符串开始(test也将推进lastIndex属性)。

从MDC文档RexExp.exec()。(参见RegExp.lastIndex)

您正在使用全局标志。因此,正则表达式只匹配特定的索引。每次匹配后,pat.lastIndex == 19,然后pat.lastIndex == 0,等等。

一个更简单的例子:

var r = /d/g;
r.exec("123"); // 1 - lastIndex == 0, so matching from index 0 and on
r.exec("123"); // 2 - lastIndex == 1, ditto with 1
r.exec("123"); // 3 - lastIndex == 2, ditto with 2
r.exec("123"); // null - lastIndex == 3, no matches, lastIndex is getting reset
r.exec("123"); // 1 - start all over again

最新更新