javascript - 将 JS Regex 捕获组存储在数组中的最佳方式?

标签 javascript regex

正是标题所问的。我将在解释我的问题时提供一些示例。

测试字符串:

var test = "#foo# #foo# bar #foo#";

比如说,我想提取 # 之间的所有文本(所有 foo 但不是 bar)。

var matches = test.match(/#(.*?)#/g);

如上使用 .match,它会存储所有匹配项,但它会简单地丢弃看起来像的捕获组。

var matches2 = /#(.*?)#/g.exec(test);

.exec 方法显然只返回数组位置 0 中第一个结果的匹配字符串,而我在位置 中唯一捕获该匹配的组1

我用尽了 SO、Google 和 MDN 寻找答案无济于事。

所以,我的问题是,有没有比使用 .exec 循环并调用 array.push 来存储匹配的捕获组更好的方法捕获组?

上面测试我期望的数组应该是:

 [0] => (string) foo
 [1] => (string) foo
 [2] => (string) foo

接受纯 JS 和 jQuery 答案,如果您使用 console.log 发布 JSFiddle,则需要额外的 cookie。 =]

最佳答案

你也可以像下面这样使用.exec来构建数组

var arr = [],
    s = "#foo# #bar# #test#",
    re = /#(.*?)#/g,
    item;

while (item = re.exec(s))
    arr.push(item[1]);

alert(arr.join(' '));​

Working Fiddle

来自 Here

嗯,它仍然有一个循环,如果你不想要一个循环,那么我认为你必须使用 .replace()。在这种情况下,代码将像

var arr = [];
var str = "#foo# #bar# #test#"
str.replace(/#(.*?)#/g, function(s, match) {
                           arr.push(match);
                        });

检查来自 MDN DOC 的这些行这解释了你关于 exec 如何更新 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 - 将 JS Regex 捕获组存储在数组中的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876338/

相关文章:

javascript - Javascript 中的异步启动器

包含 3 个或更多元音的正则表达式字符串

regex - 查找开头 t= 之后的整数

java - 正则表达式安卓

javascript - 尝试访问输入类型 ="hidden"时 getElementById 为空

javascript - 如何更改 JQGrid 的编辑对话框的大小?

java - 使用Java Regex解析xml文件

java - 按空格、连字符和 "ab cd"分割字符串

javascript - 刷新 Service Worker 中 Controller 更改的页面

javascript - WebStorm : Failed to list gulp tasks 中的 Gulp 错误