正则表达式匹配单个括号对但不匹配双括号对

sto*_*roz 2 javascript regex

是否可以使正则表达式匹配单括号内的所有内容但忽略双括号,例如:

{foo} {bar} {{baz}}
Run Code Online (Sandbox Code Playgroud)

我想匹配foo和bar而不是baz?

Tim*_*ker 7

只有匹配foobar没有周围的括号,你可以使用

(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))
Run Code Online (Sandbox Code Playgroud)

如果您的语言支持lookbehind断言.

说明:

(?<=      # 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
Run Code Online (Sandbox Code Playgroud)

编辑:在JavaScript中,你没有lookbehind.在这种情况下,您需要使用以下内容:

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);
}
Run Code Online (Sandbox Code Playgroud)