A regular expression for matching pairs with one bracket, but not pairs of double brackets

Is it possible to make a regular expression to match everything inside separate brackets, but ignore double brackets, for example, in:

{foo} {bar} {{baz}}

I want to combine foo and bar, but not baz?

+2
source share
2 answers

To match only fooand barwithout surrounding braces, you can use

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

if your language supports lookbehind statements.

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 possible to match...
 \}       #  a }
 (?!\})   #  (only if there is not another } that follows)
)         # End of lookahead

EDIT: In JavaScript, you have no 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);
}
+6
source

In many languages, you can use lookaround statements:

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

Explanation:

  • (?<!\{): {
  • \{([^}]+)\}: - , . {foo}
  • (?!\}): }
+3

Source: https://habr.com/ru/post/1685484/


All Articles