正是标题所问的。我将在解释我的问题时提供一些示例。
测试字符串:
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(' '));
来自 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/