正则表达式匹配单个括号对但不匹配双括号对 [英] Regular expression to match single bracket pairs but not double bracket pairs
本文介绍了正则表达式匹配单个括号对但不匹配双括号对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使正则表达式匹配单括号内的所有内容但忽略双括号,例如在:
Is it possible to make a regular expression to match everything within single brackets but ignore double brackets, so for example in:
{foo} {bar} {{baz}}
我想匹配foo和bar但不是baz?
I'd like to match foo and bar but not baz?
推荐答案
仅匹配 foo
和 bar
没有周围的大括号,你可以使用
To only match foo
and bar
without the surrounding braces, you can use
(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))
如果您的语言支持lookbehind断言。
if your language supports lookbehind assertions.
说明:
(?<= # 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。在这种情况下,您需要使用以下内容:
In JavaScript, you don't have lookbehind. In this case you need to use something like this:
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);
}
这篇关于正则表达式匹配单个括号对但不匹配双括号对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文