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

时间:2012-10-04 13:15:38

标签: javascript regex

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

{foo} {bar} {{baz}}

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

2 个答案:

答案 0 :(得分:7)

要仅匹配foobar没有周围的大括号,您可以使用

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

如果您的语言支持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

编辑:在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);
}

答案 1 :(得分:3)

在许多语言中,您可以使用外观断言:

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

说明:

  • (?<!\{):上一个字符不是{
  • \{([^}]+)\}:花括号内的东西,例如{foo}
  • (?!\}):以下字符不是}