2011-08-26 156 views
11

之间的字符串我有以下字符串:pass[1][2011-08-21][total_passes]正则表达式抢方括号

我将如何提取方括号之间的项目到一个数组?我试图

match(/\[(.*?)\]/);

var s = 'pass[1][2011-08-21][total_passes]'; 
 
var result = s.match(/\[(.*?)\]/); 
 

 
console.log(result);

但这只是回报[1]

不知道如何做到这一点..在此先感谢。

回答

27

你就要成功了,你只需要一个global match(注意/g标志):

match(/\[(.*?)\]/g); 

例子:http://jsfiddle.net/kobi/Rbdj4/

如果你想要的东西,只捕获组(MDN):

var s = "pass[1][2011-08-21][total_passes]"; 
var matches = []; 

var pattern = /\[(.*?)\]/g; 
var match; 
while ((match = pattern.exec(s)) != null) 
{ 
    matches.push(match[1]); 
} 

实施例:http://jsfiddle.net/kobi/6a7XN/

另一种选择(我通常喜欢),被滥用的替代回调:

var matches = []; 
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);}) 

例子:http://jsfiddle.net/kobi/6CEzP/

+0

这是返回我想要的字符串,但他们仍然在括号内 – Growler

+0

我很努力地解析多行数组内容。这里是例子。 'export const routes:Routes = {path:'',pathMatch:'full',redirectTo:'tree'}, {path:'components',redirectTo:'components/tree'}, {path:'组件/树',组件:CstdTree}, {path:'components/chips',component:CstdChips} ]; –

0

全局标志添加到您的正则表达式,并遍历数组返回。

match(/\[(.*?)\]/g) 
4
var s = 'pass[1][2011-08-21][total_passes]'; 

r = s.match(/\[([^\]]*)\]/g); 

r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ] 

example proving the edge case of unbalanced []; 

var s = 'pass[1]]][2011-08-21][total_passes]'; 

r = s.match(/\[([^\]]*)\]/g); 

r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ] 
-1

[C#]

 string str1 = " pass[1][2011-08-21][total_passes]"; 
     string matching = @"\[(.*?)\]"; 
     Regex reg = new Regex(matching); 
     MatchCollection matches = reg.Matches(str1); 

可以使用的foreach用于匹配的字符串。

0

我不确定你是否可以直接将它们存入数组中。但是,下面的代码应该努力找到所有出现,然后对其进行处理:

var string = "pass[1][2011-08-21][total_passes]"; 
var regex = /\[([^\]]*)\]/g; 

while (match = regex.exec(string)) { 
    alert(match[1]); 
} 

请注意:我真的觉得你需要的字符类[^ \]这里。否则,在我的测试中,表达式将与孔串匹配,因为]也与。*匹配。