正则表达式在方括号之间抓取字符串 [英] Regex to grab strings between square brackets

查看:177
本文介绍了正则表达式在方括号之间抓取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

How would I extract the items between the square brackets into an array? I tried

匹配(/ \ [(。*?)\] /);

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

console.log(result);

但这只返回 [1]

不知道如何做到这一点..提前谢谢。

Not sure how to do this.. Thanks in advance.

推荐答案

你几乎就在那里,你只需要一个全球匹配(请注意 / g flag):

You are almost there, you just need a global match (note the /g flag):

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

示例: http://jsfiddle.net/kobi/Rbdj4/

如果你想要的东西只捕获组(来自 MDN ):

If you want something that only captures the group (from 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/

另一种选择(我通常更喜欢),滥用替换回调:

Another option (which I usually prefer), is abusing the replace callback:

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

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

这篇关于正则表达式在方括号之间抓取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆