简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM