javascript - 使用 exec 查找多个匹配 JavaScript

标签 javascript regex exec

我在解释 MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec 中的以下代码时遇到问题

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

我对 while 循环线感到困惑。它似乎将 myArray 设置为对字符串 str 调用 exec 的结果,并表示如果它不等于 null 则继续。

我不明白的是程序如何知道从找到匹配项的最后一个索引开始搜索。对我来说,这看起来应该是一个无限循环 b/c 我看不到它说从数组中的下一个索引开始搜索的位置。

此外,是否有任何理由使用 exec 来查找多个匹配项而不仅仅是使用 match ? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

最佳答案

lastIndex一旦您将带有全局修饰符的正则表达式传递给 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).

另请参阅15.10.6.2 RegExp.prototype.exec(string) 确切的 RegExp#exec眼镜。特别是:

  1. If global is true,
      a. Call the [[Put]] internal method of R with arguments "lastIndex", e, and true.

由于模式与 unanchored 空字符串不匹配,因此不会发生无限循环。是var myRe = /ab*/g; ,所以a在输入中必须返回有效的匹配项。如果是var myRe = /a*/g; ,那么就会出现无限循环。

另外,请检查Zero-Length regexes and infinite matches?线程。

关于javascript - 使用 exec 查找多个匹配 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131129/

相关文章:

javascript - 如何在 javascript 中制作图像 slider

Java正则表达式找到不在字符范围内的第一个字符

linux - execvp 后 QEMU 无终端输出

c - fork() 和 exec() : parameter with space

javascript - 如何在 Angular 中使用 Datatables.Net 创建自定义打印预览屏幕

javascript - 如何用 Deno 编写 TCP 聊天服务器?

jquery - JS 不接受 <> 大于或小于符号

R - 正则表达式根据第一个点分隔字符串?

sql-server-2008 - 设置@var = exec存储过程

javascript - 可调整大小和可旋转的矩形 D3?