您的位置:首页 > 其它

一个小正则问题的研究

2013-04-03 11:27 253 查看
今天发现一个很有意思的正则代码,题目很简单

var reg =/123/g;
var str = "123#abc";
console.log(reg.test(str)); //true
console.log(reg.test(str)); //false
console.log(reg.test(str)); //true
console.log(reg.test(str)); //false


  

看似很简单,但是运行结果却让我很纳闷,What's happened?
是因为test的返回值吗?test()之后返回boolean不会有影响的应该,那么问题出在哪呢?
咱们先来分析下ECMAScript中这段程序是如何执行的


1. Let S be the value of ToString(string).
2. Let length be the length of S.
3. Let lastIndex be the value of the lastIndex property.
4. Let i be the value of ToInteger(lastIndex).
5. If the global property is false, let i = 0.
6. If I < 0 or I > length then set lastIndex to 0 and return null.
7. Call [Match], giving it the arguments S and i. If [Match] returned failure, go to step 8;
otherwise let r be its State result and go to step 10.
8. Let i = i+1.
9. Go to step 6.
10. Let e be r's endIndex value.- 145 -
11. If the global property is true, set lastIndex to e.
12. Let n be the length of r's captures array. (This is the same value as 15.10.2.1's
NCapturingParens.)
13. Return a new array with the following properties:
• The index property is set to the position of the matched substring within the complete string
S.
• The input property is set to S.
• The length property is set to n + 1.
• The 0 property is set to the matched substring (i.e. the portion of S between offset i inclusive
and offset e exclusive).
• For each integer i such that I > 0 and I ≤ n, set the property named ToString

to the i
th element
of r's captures array.


原来都是“g”惹的祸。首先要知道正则有个lastIndex属性,如果有 g 这个标志位,那么lastIndex就会存储上次匹配到的字符串的最后一个index位,然后在下一次查找的时候就从lastIndex进行查找,因此我们就可以明白为什么第二次和第四次的返回值是false了。
接下来咱们来验证一下

var reg =/123/g;
var str = "123#abc";
console.log(reg.lastIndex); //0
console.log(reg.test(str)); //true
console.log(reg.lastIndex); //3
console.log(reg.test(str)); //false
console.log(reg.lastIndex); //0
console.log(reg.test(str)); //true
console.log(reg.lastIndex); //3
console.log(reg.test(str)); //false
console.log(reg.lastIndex); //0


  

看到这样的运行结果,您也就能明白为什么了

Javascript还有很多坑等待着我们去慢慢发现,这也是我前进的动力
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: