正则表达式抓取方括号之间的字符串
我有以下字符串: 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]
。
不知道该怎么做..提前致谢。
I have the following string: pass[1][2011-08-21][total_passes]
How would I extract the items between the square brackets into an array? I tried
match(/\[(.*?)\]/);
var s = 'pass[1][2011-08-21][total_passes]';
var result = s.match(/\[(.*?)\]/);
console.log(result);
but this only returns [1]
.
Not sure how to do this.. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你就快到了,你只需要一个全局匹配(注意< code>/g 标志):
示例:http://jsfiddle.net/kobi/Rbdj4/
如果您想要仅捕获组的内容(来自 MDN):
示例:http://jsfiddle.net/kobi/6a7XN/
另一种选择(我通常更喜欢)是滥用替换回调:
示例: http://jsfiddle.net/kobi/6CEzP/
You are almost there, you just need a global match (note the
/g
flag):Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
Example: http://jsfiddle.net/kobi/6CEzP/
将全局标志添加到您的正则表达式中,并迭代返回的数组。
add the global flag to your regex , and iterate the array returned .
我不确定你是否可以将其直接放入数组中。但以下代码应该可以找到所有出现的情况,然后处理它们:
请注意:我真的认为您需要此处的字符类 [^\]]。否则,在我的测试中,表达式将与空字符串匹配,因为 ] 也与 .* 匹配。
I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:
Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.
说明
您可以使用正则表达式的其他组合
https://regex101.com/r/IYDkNi/1
Explanation
You can play with other combinations of the regular expression
https://regex101.com/r/IYDkNi/1
[C#]
您可以使用 foreach 来匹配字符串。
[C#]
you can use foreach for matched strings.