在字符串中查找所有匹配的正则表达式模式和匹配的索引

yot*_*moo 7 javascript regex

我想/AA/AA-AA-AA主题字符串中找到模式.我需要获得匹配的字符串和匹配的位置(索引).

我看过了RegExp.prototype.exec().它只返回第一个匹配:

/AA/g.exec('AA-AA-AA')
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 18

exec()只返回一个匹配.要获得所有匹配的global regexp,你必须重复调用它,例如:

var match, indexes= [];
while (match= r.exec(value))
    indexes.push([match.index, match.index+match[0].length]);
Run Code Online (Sandbox Code Playgroud)

  • @bobince那不是真的.假设正在使用的正则表达式不是全局的,`String.prototype.match`和`RegExp.prototype.exec`返回相同的东西.在chrome,firefox和ie中测试过.此外,Ecma-262建议`match`应该在内部使用`exec`:http://bclary.com/2004/11/07/#a-15.5.4.10 (2认同)
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match 如果正则表达式不包含 `g` 标志,`str.match()` 将返回与`RegExp.exec()` 相同的结果如果包含`g` 标志,`str.match()` 返回一个包含所有匹配子字符串而不是匹配对象的数组,不返回捕获的组 (2认同)