2

我一直在调试这个应用程序一段时间,它引导我进入这个测试用例。当我在 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

这里发生了什么?

4

2 回答 2

4

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

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

来自 RexExp.exec() 的 MDC 文档。(另见RegExp.lastIndex

于 2011-08-24T17:07:21.137 回答
2

您正在使用全局标志。因此,正则表达式仅匹配特定索引。在每场比赛之后,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
于 2011-08-24T17:07:38.850 回答