ak85
ak85

Reputation: 4264

regex include text inside brackets

I want to alert the text inside brackets. I can do this when I have square brackets.

    a = "1[the]"
    words = a.match(/[^[\]]+(?=])/g);
    alert(words);

But I can't get it going with round brackets ()

I have tried a few different things but don't quite have my head around what I need to change here.

    a = "1(the)"
    words = a.match(/(^[\])+(?=])/g);
    alert(words);

    a = "1(the)"
    words = a.match(/[^(\)]+(?=])/g);
    alert(words);

    a = "1(the)"
    words = a.match(/[^[\]]+(?=))/g);
    alert(words);

    a = "1(the)"
    words = a.match(/[^[\]]+(?=])/g);
    alert(words);

Where am I going wrong?

Upvotes: 0

Views: 1036

Answers (2)

mathematical.coffee
mathematical.coffee

Reputation: 56915

You current regex doesn't technically look for words inside brackets. For example, if the string was "foobar)" it would match "foobar".

Try something like:

a = "1(the) foo(bar)"
regexp = /\((.*?)\)/g

// loop through matches
match = regexp.exec(a)
while (match != null) {
    alert(match[1]) # match[1] is captured group 1
    match = regexp.exec(a)
}

Upvotes: 1

Ryan J
Ryan J

Reputation: 8323

The ()'s need to be escaped. They have special meaning, in that they are used to 'capture' specific groups of text matched by the pattern between them.

Edited to fix an issue with the way I interpreted the problem. Try again, this should work.

Try this:

a = "1(the)"
words = a.match(/[^\(\)]+(?=\))/g);
alert(words);

Upvotes: 1

Related Questions