如何从单个RegEx获得多个匹配

时间:2014-10-17 01:38:19

标签: javascript regex

我目前正在使用Javascript并且正在尝试处理一些正则表达式。我想要做的是,有一个类似这样的字符串:

this is a test [type:string] further test [type:string]

我想要做的是,能够使用正则表达式来获取每组括号之间的文本。最终,我想分别以这两个值结束,或者在一个列表中一起结束(即使它们是相同的也能区分它们)

所以我想出去

[类型:字符串] [类型:字符串]

两次。

我知道我可以这样做:

\[(.*?)\]

但是当我这样做时,它只匹配第一个括号集,我希望它匹配所有这些,我似乎无法找到一种方法来做到这一点。任何帮助都会很棒。谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用g修饰符(全局匹配):



var string = 'this is a test [type:string1] further test [type:string2]';

var matches = string.match(/\[(.*?)\]/g);

console.log(matches);




答案 1 :(得分:2)

您可以单独提取每个值:

var str = "this is a test [type:number] further test [type:string]";
var reg = /\[([a-z]+):([a-z]+)\]/g;
while (match = reg.exec(str)) {
   console.log("type=" + match[1], " and value=" + match[2]);
}

将记录:

type=type and value=number
type=type and value=string

或仅适用于[]:

中的值
var str = "this is a test [type:number] further test [type:string]";
var reg = /\[([a-z:]+)\]/g;
while (match = reg.exec(str)) {
   console.log("type: " + match[1]);
}

将记录:

type: type:number
type: type:string

我还使您的RegEx更加具体。因此,一旦进入解析真实文本,您就不会遇到不正确的结果。