执行 Regex.exec(testString) 时正则表达式的奇怪行为
Regex'es weird behavior when doing Regex.exec(testString)
我可以知道为什么以下语句会发生以下奇怪的行为吗?
a = /\d+/gi
outputs `/\d+/gi`
a.exec('test1323')
outputs `["1323"]`
再一次 运行 同样的陈述给出
a.exec('test1323')
null
即使我尝试使用新的 Regex("regex string") 创建正则表达式,但仍然没有任何变化。
请看附件
它发生在 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的更长时间干运行。
我可以知道为什么以下语句会发生以下奇怪的行为吗?
a = /\d+/gi
outputs `/\d+/gi`
a.exec('test1323')
outputs `["1323"]`
再一次 运行 同样的陈述给出 a.exec('test1323')
null
即使我尝试使用新的 Regex("regex string") 创建正则表达式,但仍然没有任何变化。
请看附件
它发生在 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的更长时间干运行。