views:

345

answers:

5

I need to return just the text contained within square brackets in a string. I have the following regex, but this also returns the square brackets:

var matched = mystring.match("\\[.*]");

A string will only ever contain one set of square brackets, e.g.:

Some text with [some important info]

I want matched to contain 'some important info', rather than the '[some important info]' I currently get.

A: 

Did you try capturing parens:

("\[(.*)]");

This should return the pattern within the brackets as a captured match in the returned array

ennuikiller
A: 

You can't. Javascript doesn't support lookbehinds.

You'll have to either use a capture group or trim off the brackets.

By the way, you probably don't want a greedy .* in your regex. Try this:

"\\[.*?]"

Or better, this:

"\\[[^\\]]*]"
Jeremy Stein
A: 

if you're not set on entirely using RegEx, there's always the string.replace() function. e.g: string.replace('[','');

pixelbobby
+5  A: 

Use grouping. I've added a ? to make the matching "ungreedy", as this is probably what you want.

var matches = mystring.match(/\[(.*?)\]/);

if (matches) {
    var submatch = matches[1];
}
Alex Barrett
A: 

Since javascript doesn't support captures, you have to hack around it. Consider this alternative which takes the opposite approach. Rather that capture what is inside the brackets, remove what's outside of them. Since there will only ever be one set of brackets, it should work just fine. I usually use this technique for stripping leading and trailing whitespace.

mystring.replace( /(^.*\[|\].*$)/g, '' );
spudly