是否可以使正则表达式匹配单括号内的所有内容但忽略双括号,例如在:
{foo} {bar} {{baz}}
我想匹配foo和bar而不是baz?
答案 0 :(得分:7)
要仅匹配foo
和bar
没有周围的大括号,您可以使用
(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))
如果您的语言支持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}
(?!\})
:以下字符不是}