在下不才 请各位看官 求解js正则问题
发布于 11 年前 作者 llj732589025 4732 次浏览 最后一次编辑是 8 年前

代码如下:

>var a=/\d+/g
undefined

>a.exec('a2a')
['2',index:1,input:'a2a']

>a.exec('a1a')
null

>/\d+/g.exec('a2a')
['2',index:1,input:'a2a']

>/\d+/g.exec('a1a')
['1',index:1,input:'a1a']

为什么第二次执行就会返回null而不是正确的

6 回复

把 lastIndex 设置为 0 。

lastIndex 这个参数在哪里的啊?能写个例子吗

var a=/\d+/g a.exec(‘a2a’) //[‘2’] a.lastIndex = 0 a.exec(‘a1a’); //[‘1’]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

If your regular expression uses the “g” flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression’s lastIndex property (test will also advance the lastIndex property). For example, assume you have this script:

var myRe = /ab*/g;
var str = "abbcdefabh";
var myArray;
while ((myArray = myRe.exec(str)) !== null)
{
  var msg = "Found " + myArray[0] + ".  ";
  msg += "Next match starts at " + myRe.lastIndex;
  console.log(msg);
}

谢啦 原来这样写对于js来说也是一个RegExp对象导致的

但是,当 RegExpObject 是一个全局正则表达式时,exec() 的行为就稍微复杂一些。它会在 RegExpObject 的 lastIndex 属性指定的字符处开始检索字符串 string。当 exec() 找到了与表达式相匹配的文本时,在匹配后,它将把 RegExpObject 的 lastIndex 属性设置为匹配文本的最后一个字符的下一个位置。这就是说,您可以通过反复调用 exec() 方法来遍历字符串中的所有匹配文本。当 exec() 再也找不到匹配的文本时,它将返回 null,并把 lastIndex 属性重置为 0

回到顶部