4

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

{foo} {bar} {{baz}}

我想匹配 foo 和 bar 但不匹配 baz?

4

2 回答 2

9

要仅匹配foo并且bar不匹配周围的大括号,您可以使用

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

如果您的语言支持后向断言。

解释:

(?<=      # 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

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

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);
}
于 2012-10-04T13:19:05.203 回答
3

在许多语言中,您可以使用环视断言:

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

解释:

  • (?<!\{): 前一个字符不是{
  • \{([^}]+)\}:大括号内的东西,例如{foo}
  • (?!\}): 后面的字符不是}
于 2012-10-04T13:17:12.447 回答