2011-08-26 277 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]); 
} 

請注意:我真的覺得你需要的字符類[^ \]這裏。否則,在我的測試中,表達式將與孔串匹配,因爲]也與。*匹配。