javascript - 正则表达式在执行 Regex.exec(testString) 时的奇怪行为

标签 javascript regex google-chrome

我可以知道为什么以下语句会发生以下奇怪的行为吗?

a = /\d+/gi
outputs `/\d+/gi`
a.exec('test1323')
outputs `["1323"]`

并再次运行相同的语句给出 a.exec('test1323')

null

即使我尝试使用 new Regex("regex string") 创建正则表达式,但仍然没有变化。

请见附件enter image description here

它发生在 Chrome 控制台中。

最佳答案

您正在创建带有 g 标志的正则表达式。当您这样做时,exec方法会记住最后一个匹配的位置,并从最后一个匹配开始匹配。结果解释如下:

> a = /\d+/gi
< /\d+/gi  // a.lastIndex is initialized to 0
> a.exec("test1323")
< ["1323"] // match begins at 0, match found at index 4...7, a.lastIndex is now 8
> a.exec("test1323")
< null     // match begins at 8, no match found, a.lastIndex is reset to 0
> a.exec("test1323")
< ["1323"] // match begins at 0, match found at index 4...7, a.lastIndex is now 8

类似问题的较长时间演练 can be found in this answer .

关于javascript - 正则表达式在执行 Regex.exec(testString) 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111033/

相关文章:

javascript - 如何动态删除 Bootstrap 网格中的列?

javascript - JS 上的 Match() 与正则表达式返回 NULL

ruby-on-rails - 如何在ruby中解析字符串中最后一组括号之间的子字符串

javascript - 可打开和关闭的 Chrome 扩展程序

google-chrome - 为什么 chrome 在资源选项卡中显示所有域的 cookie

javascript - Backbone 模型创建 |概念理解

javascript - 第一个滚动脚本之后的 fullpage.js

javascript - 从字符串中删除特殊字符(如果它们单独存在且不属于单词的一部分)

javascript - Chrome Timeline 中的 JS 瓶颈

javascript - 从下拉列表中获取牵引值