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

时间:2011-08-26 07:33:23

标签: 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);

但这仅返回[1]

不确定如何做到这一点..提前致谢。

6 个答案:

答案 0 :(得分:30)

你快到了,你只需要一个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/

答案 1 :(得分: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]' ]

答案 2 :(得分:1)

将全局标志添加到正则表达式,并迭代返回的数组。

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

答案 3 :(得分:0)

我不确定你是否可以将它直接放入数组中。但是下面的代码应该可以找到所有出现的事件,然后处理它们:

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

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

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

答案 4 :(得分:0)

'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]

说明

\[       # match the opening [
           Note: \ before [ tells that do NOT consider as a grouping symbol.
   .+?   # Accept one or more character but NOT greedy
\]       # match the closing ] and again do NOT consider as a grouping symbol
/g       # do NOT stop after the first match. Do it for the whole input string.

您可以使用正则表达式的其他组合 https://regex101.com/r/IYDkNi/1

答案 5 :(得分:-1)

[C#]

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

你可以使用foreach来匹配字符串。