问题描述
当我跑步时
/(a)/g.exec('a a a ').length
我得到
2
但我认为应该返回
3
因为有3 字符串中的
s,而不是2!
because there are 3 a
s in the string, not 2!
为什么会这样?
我希望能够在RegEx中搜索字符串的所有出现并迭代它们。
I want to be able to search for all occurances of a string in RegEx and iterate over them.
FWIW:我正在使用node.js
FWIW: I'm using node.js
推荐答案
exec()
仅返回第一个匹配的捕获集,而不是集合你期望的比赛所以你真正看到的是 $ 0
(整个匹配,a)和 $ 1
(第一次捕获) ) - 即长度为2的数组。 exec()
同时设计为可以再次调用 来获取 next 匹配。来自:
exec()
is returning only the set of captures for the first match, not the set of matches as you expect. So what you're really seeing is $0
(the entire match, "a") and $1
(the first capture)--i.e. an array of length 2. exec()
meanwhile is designed so that you can call it again to get the captures for the next match. From MDN:
这篇关于Javascript:如何在RegEx .exec结果中获得多个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!