将JS Regex捕获组存储在数组中的最佳方法? [英] Best way to store JS Regex capturing groups in array?

查看:49
本文介绍了将JS Regex捕获组存储在数组中的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确切地标题是什么.我将在解释我的问题时提供一些示例.

Exactly what title asks. I'll provide some examples while explaining my question.

测试字符串:

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

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

Say, I want to extract all text between # (all foos but not bar).

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

使用上面的 .match ,它将存储所有匹配项,但只是简单地丢弃看起来似乎的捕获组.

Using .match as above, it'll store all matches but it'll simply throw away the capturing groups it seems.

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

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

The .exec method apparently returns only the first result's matched string in the position 0 of the array and my only capturing group of that match in the position 1.

我已经用尽SO,Google和MDN寻求无济于事的答案.

I've exhausted SO, Google and MDN looking for an answer to no avail.

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

So, my question is, is there any better way to store only the matched capturing groups than looping through it with .exec and calling array.push to store the captured groups?

我期望上述测试的数组为:

My expected array for the test above should be:

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

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

Pure JS and jQuery answers are accepted, extra cookies if you post JSFiddle with console.log. =]

推荐答案

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

You can use .exec too like following to build an array

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

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

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

工作小提琴

此处找到.

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

Well, it still has a loop, if you dont want a loop then I think you have to go with .replace(). In which case the code will be like

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

MDN DOC 中检查这些行,它解释了您的查询关于 exec 如何更新我认为的 lastIndex 属性,

Check these lines from MDN DOC which explains your query about howexec updates lastIndex property I think,

如果您的正则表达式使用"g"标志,您可以使用exec方法多次,以在同一字符串中查找连续的匹配项.

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string.

这样做时,搜索从以下指定的str的子字符串开始正则表达式的lastIndex属性(测试也将前进lastIndex属性).

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

这篇关于将JS Regex捕获组存储在数组中的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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