是否可以使正则表达式匹配单括号内的所有内容但忽略双括号,例如:
{foo} {bar} {{baz}}
我想匹配 foo 和 bar 但不匹配 baz?
最佳答案
只匹配 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);
}
关于javascript - 正则表达式匹配单括号对但不匹配双括号对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728128/