Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

but this only returns [1].

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

like image 816
Joris Ooms Avatar asked Aug 26 '11 07:08

Joris Ooms


People also ask

How do you match square brackets in regex?

[[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

How do you escape square brackets in regex?

An escape can be either enclosing the phrase in braces, or placing a backslash before the escaped character. To pass a left bracket to the regular expression parser to evaluate as a range of characters takes 1 escape.

What do the [] brackets mean in regular expressions?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

How do you put text in between brackets?

Extract Text Between Parenthesis To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.


2 Answers

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/

like image 142
Kobi Avatar answered Sep 28 '22 18:09

Kobi


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]' ]
like image 40
James Kyburz Avatar answered Sep 28 '22 19:09

James Kyburz