标签:tin 输入 class nbsp 正则表达 成功 .exe regex 多个
关于正则表达式匹配中获取所有匹配点时,匹配点的开始位置遇到的问题
<script type="text/javascript">
var txt = ‘If you love code, you should code everyday.‘;
var reg = new RegExp(‘ou‘, ‘g‘);
var length = txt.match(reg).length;
for(var i = 0; i < length; i++) {
reg.test(txt);
console.log(reg.lastIndex);
}
</script>
输出结果如下:

<script type="text/javascript">
var txt = ‘If you love code, you should code everyday.‘;
var reg = new RegExp(‘ou‘, ‘g‘);
var length = txt.match(reg).length;
reg.test(txt);
for(var i = 0; i < length; i++) {
console.log(reg.lastIndex);
}
</script>
输出结果如下:

第二段代码输出结果的原因是正则表达式只使用了一次,正则对象中记录的是此次匹配所找到的匹配点,导致三次输出结果相同
对于正则对象中每次进行匹配的匹配点进行了如下测试:
1.改变字符串长度
<script type="text/javascript">
var txt = ‘If you love code, you should code everyday.‘;
var reg = new RegExp(‘ou‘, ‘g‘);
while(t = reg.exec(txt)) {
console.log(t, reg.lastIndex, txt);
txt = ‘If you love code, you ‘;
}
</script>
输出结果如下:

正则的后续匹配使用新的字符串,如果新字符串改变匹配项的位置呢?
2.改变字符串中匹配项"ou"的位置
<script type="text/javascript">
var txt = ‘If you love code, you should code everyday.‘;
var reg = new RegExp(‘ou‘, ‘g‘);
while(t = reg.exec(txt)) {
console.log(t, reg.lastIndex, txt);
txt = ‘If yo loue code, you ‘;
}
</script>
输出结果如下:

输出结果中新字符串中的所有匹配点都匹配成功,那是否代表下一次匹配开始的匹配点为上一次匹配中的lastIndex呢?
3.在上一次匹配中的lastIndex前加入多个匹配项
<script type="text/javascript">
var txt = ‘If you love code, you should code everyday.‘;
var reg = new RegExp(‘ou‘, ‘g‘);
while(t = reg.exec(txt)) {
console.log(t, reg.lastIndex, txt);
txt = ‘ouIouf yo loue code, you ‘;
}
</script>
输出结果如下:

输入结果显示第二个匹配点从index = 11进行匹配,而index = 6前边的两个匹配项并没有匹配到
最后得出的结论是同一个正则表达式下一次匹配开始位置,为上一次匹配结束的位置+1
标签:tin 输入 class nbsp 正则表达 成功 .exe regex 多个
原文地址:http://www.cnblogs.com/MrShy/p/6363333.html