[英]Regex to grab strings between square brackets
我有以下字符串: 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]
。
不知道该怎么做.. 提前致谢。
你快到了,你只需要一个全局匹配(注意/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);})
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]' ]
将全局标志添加到您的正则表达式,并迭代返回的数组。
match(/\[(.*?)\]/g)
'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
我不确定您是否可以将其直接放入数组中。 但是下面的代码应该可以找到所有出现的情况然后处理它们:
var string = "pass[1][2011-08-21][total_passes]";
var regex = /\[([^\]]*)\]/g;
while (match = regex.exec(string)) {
alert(match[1]);
}
请注意:我真的认为您需要这里的字符类 [^\\]]。 否则,在我的测试中,表达式将匹配孔字符串,因为 ] 也与 .* 匹配。
[C#]
string str1 = " pass[1][2011-08-21][total_passes]";
string matching = @"\[(.*?)\]";
Regex reg = new Regex(matching);
MatchCollection matches = reg.Matches(str1);
您可以将 foreach 用于匹配的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.