Javascript:如何在RegEx .exec结果中获得多个匹配项 [英] Javascript: How to get multiple matches in RegEx .exec results

查看:1231
本文介绍了Javascript:如何在RegEx .exec结果中获得多个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我跑步时

/(a)/g.exec('a a a ').length

我得到

2

但我认为应该返回

3

因为有3 字符串中的 s,而不是2!

because there are 3 as 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 <的捕获/ em>匹配。来自 MDN

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:


如果正则表达式使用g标志,则可以多次使用exec方法在同一个字符串中查找连续匹配。执行此操作时,搜索从正则表达式的lastIndex属性指定的str的子字符串开始(test也将使lastIndex属性前进)。

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).

这篇关于Javascript:如何在RegEx .exec结果中获得多个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆