2014-10-17 83 views
0

我目前正在使用Javascript,并试图处理一些正则表达式。我想要做的是,有一个字符串,它是这样的:如何从单一正则表达式获得多个匹配

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

我想要做的,是能够使用正则表达式来获得各组括号之间的文本。最后,我想在一个列表(能告诉他们分开,即使它们是相同的)

所以我会想摆脱这些2个值落得单独或一起

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

两次。

我知道我可以利用这样做:

\[(.*?)\] 

但是当我做,它只匹配的第一个支架一套,我希望它符合所有这些,我似乎无法找到一个方法来做到这一点。任何帮助都会很棒。谢谢!

回答

3

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

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

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

 
console.log(matches);

+0

这最终为我做了。非常感谢! – user2146933 2014-10-21 22:14:07

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 

我还做你的正则表达式的更具体一点。所以一旦你解析真实的文本,你就不会遇到不正确的结果。

相关问题