不寻常的javascript正则表达式结果,请说明! [英] Unusual javascript Regex result, explanation please!
问题描述
我正在VS2005中开发并在我的页面中有一些JS代码。我在一个特定的循环中设置了一个断点,我遇到了一个问题。这是我与IDE的小谈话 -
I'm developing in VS2005 and have some JS code in my page. I have set a breakpoint during a particular loop where I was having an issue. Here is my little conversation with the IDE--
? ind
/d/g
? ind.test("d")
true
? ind.test("dtn")
false
? ind.test("dtn")
true
? ind.test("dtn")
false
? ind.test("dtn")
true
? ind.test("dtn")
false
为什么测试在true和假? ind
是我的RegEx - 我这样设置:
Why is the test alternating between true and false? ind
is my RegEx - I set it like this:
case "datetime" : ind = new RegExp("d","g");break;
UPDATE
所以我已经解决了我的问题是将我的声明改为
UPDATE
So I've solved my issue by changing my declaration to
ind = /d/;
即省略全局修饰符。我想那是
ie omitting the global modifier. I suppose that
ind = RegExp("d");
同样也可以。
问题仍然存在。为什么导致 test
的全局修饰符在true和false之间交替?
The question remains though. Why was the global modifier causing the test
to alternate between true and false?
推荐答案
与exec一样(或与
组合),在
上多次调用相同的全局正则表达式
实例将超过
上一场比赛。
As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
来源: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/test
所以这里究竟发生了什么,因为你正在使用正则表达式的全局选项,它会在找到匹配后继续搜索字符串。
So what exactly happens here is that since you're using the global option for the regex, it will continue to search the string after it found an match.
ind.test("d")
这将找到d在位置0 。
ind.test("d")
现在将从
This will now search for d starting at position 1, but since that's the end of the string it will not find anything therefore returning false.
我们可以使用正则表达式的 lastIndex
属性来证明:
We can use the lastIndex
property of the regex to proof that:
ind.lastIndex
>> 0
ind.test("d")
>> true
ind.lastIndex
>> 1
ind.test("d")
>> false
这篇关于不寻常的javascript正则表达式结果,请说明!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!