正则表达式在方括号之间抓取字符串

cab*_*ret 15 javascript regex match

我有以下字符串: pass[1][2011-08-21][total_passes]

如何将方括号之间的项目提取到数组中?我试过了

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

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

console.log(result);
Run Code Online (Sandbox Code Playgroud)

但这只会返回[1].

不知道怎么做...提前谢谢.

Kob*_*obi 30

你几乎就在那里,你只需要一个全局匹配(注意/g标志):

match(/\[(.*?)\]/g);
Run Code Online (Sandbox Code Playgroud)

示例: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]);
}
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/kobi/6a7XN/

另一个选项(我通常更喜欢)是滥用替换回调:

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

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


Jam*_*urz 5

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]' ]
Run Code Online (Sandbox Code Playgroud)