views:

33

answers:

1

Hi, Can someone help me with a Javascript regular expression? I need to match pairs of brackets. For example, it should match "[abc123]", "[123abc]" in the following string:

"this is a test [abc123]], another test [[123abc]. This is an left alone closing"

Thanks in advance.

+2  A: 

If you don't require nested brackets,

// theString = "this is a test [abc123]], another test [[123abc]. This is an left alone closing";
return theString.match(/\[[^\[\]]*\]/g);
// returns ["[abc123]", "[123abc]"]

to extract the contents,

var rx = /\[([^\[\]]*)\]/g;
var m, a = [];
while((m = rx.exec(theString))
  a.push(m[1]);
return a;
KennyTM
Beat me to it :(
puddingfox