简体   繁体   中英

Regular expression to match single bracket pairs but not double bracket pairs

Is it possible to make a regular expression to match everything within single brackets but ignore double brackets, so for example in:

{foo} {bar} {{baz}}

I'd like to match foo and bar but not baz?

To only match foo and bar without the surrounding braces, you can use

(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))

if your language supports lookbehind assertions.

Explanation:

(?<=      # Assert that the following can be matched before the current position
 (?<!\{)  #  (only if the preceding character isn't a {)
\{        #  a {
)         # End of lookbehind
[^{}]*    # Match any number of characters except braces
(?=       # Assert that it's possible to match...
 \}       #  a }
 (?!\})   #  (only if there is not another } that follows)
)         # End of lookahead

EDIT: In JavaScript, you don't have lookbehind. In this case you need to use something like this:

var myregexp = /(?:^|[^{])\{([^{}]*)(?=\}(?!\}))/g;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 0; i < match.length; i++) {
        // matched text: match[1]
    }
    match = myregexp.exec(subject);
}

In many languages you can use lookaround assertions:

(?<!\{)\{([^}]+)\}(?!\})

Explanation:

  • (?<!\\{) : previous character is not a {
  • \\{([^}]+)\\} : something inside curly braces, eg {foo}
  • (?!\\}) : following character is not 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