有趣的Javascript RegExp测试 [英] Interesting test of Javascript RegExp

查看:95
本文介绍了有趣的Javascript RegExp测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Javascript RegExp测试来检测日期字符串格式,我错误地添加了一个冗余的g标记并找到了一些有趣的东西。

I wrote a Javascript RegExp test to detect date string format, I added an redundant "g" flag by mistake and found something interesting.

var s = "2009/03/10";
var regex=/^\d{4}[/]\d{2}[/]\d{2}$/g;
alert(regex.test(s));
alert(regex.test(s));
alert(regex.test(s));
alert(regex.test(s));

我得到一个'true'后跟一个'false',然后是另一个'true',然后是另一个'false'。

I got a 'true' followed by a 'false', then another 'true', then another 'false'.

如果我使用循环来执行它,我发现了一些更有趣的东西,我在IE和Safari中得到了四个真实,而且是真的,假的,在FF,Chrome中为true,false。

If I use a loop to execute it, I found something more interesting, I got four "true" in IE and Safari, and true,false,true,false in FF, Chrome.

for (var i=0; i<4; i++)
{
  var s = "2009/03/10";
  var regex=/^\d{4}[/]\d{2}[/]\d{2}$/g;
  alert(regex.test(s));
}

有没有人有理由解释为什么Javascript正则表达式的行为和原因是什么?浏览器返回不同结果? (与变量声明和生命范围有关?)

Does anybody has idea to explain why the Javascript regex behaves like that and what cause browsers return different results? ( related to variable declaration and life scope? )

推荐答案

当你在JS RegExp上使用全局标志时,test和exec方法每次在第一次匹配时停止,但保留指向它们停止在字符串中搜索的位置的指针。可以在 lastIndex 属性上检查该指针。当你再次调用test或exec时,它开始搜索从 lastIndex 开始的匹配。

When you use a global flag on a JS RegExp the "test" and "exec" methods each halt at the first match but keep a pointer to where they stopped searching in the string. That pointer can be inspected on the lastIndex property. When you call "test" or "exec" again it begins searching for a match starting at the lastIndex.

因此,当您在匹配整个字符串的字符串上测试RegExp时,lastIndex将设置为字符串的结尾。下次测试时,从字符串末尾开始,返回 false ,并将 lastIndex 设置为零。

So, when you test a RegExp on a string that matches the entire string the lastIndex is set to the end of the string. The next time you test it starts at the end of the string, returns false, and sets lastIndex back to zero.

MDC有

The MDC has a decent explanation of this behavior.

这篇关于有趣的Javascript RegExp测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆