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

标签 javascript regex

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

{foo} {bar} {{baz}}

我想匹配 foo 和 bar 但不匹配 baz?

最佳答案

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

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

如果您的语言支持后向断言。

解释:
(?<=      # 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/

相关文章:

javascript - 将模型转换为数组 mvc 3

java - 如何使用正则表达式来匹配此模式

java - 返回文本中给定位置前后指定数量的单词

javascript - JavaScript中instanceof是如何实现的

javascript - 用于 SMS 消息传递的 window.location.href - 平台兼容性

Javascript/JQuery Datagrid 在数据表中显示/编辑/输入

c# - 简单的 ASP.Net 问题 <%# 和 <%= 不起作用!

python - 排除匹配模式中的一列

java - float 至 java 货币

ruby - StringScanner 正在匹配一个字符串,就好像它向后一个位置一样