![](/img/trans.png)
[英]How to match nested function invocations (bracket pairs) using a regular expression (recursive?)
[英]Regular expression to match single bracket pairs but not double bracket pairs
是否可以使正則表達式匹配單括號內的所有內容但忽略雙括號,例如:
{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);
}
在許多語言中,您可以使用環視斷言:
(?<!\{)\{([^}]+)\}(?!\})
解釋:
(?<!\\{)
: 前一個字符不是{
\\{([^}]+)\\}
:花括號內的東西,例如{foo}
(?!\\})
: 后面的字符不是}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.