跳到主要内容
CNode

在下不才 请各位看官 求解js正则问题

社区
Lllj732589025发布于 13 年前最后回复 13 年前
661120

代码如下:

>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)

C
chihuohuo#613 年前

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

L
llj732589025#513 年前
引用 yimityvar a=/\d+/g a.exec('a2a') //['2'] a.lastIndex = 0 a.exec('a1a'); //['1']

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

H
hankwang#413 年前

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);
}
Y
yimity#313 年前

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

L
llj732589025#213 年前
引用 yimity把 lastIndex 设置为 0 。

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

Y
yimity#113 年前

把 lastIndex 设置为 0 。

参与回复

登录后即可参与回复。登录