Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

javascript - Regex to grab strings between square brackets

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Example: http://jsfiddle.net/kobi/Rbdj4/

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]);
}

Example: 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);})

Example: http://jsfiddle.net/kobi/6CEzP/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...