Java RegEx组是否可以否定?

时间:2012-03-15 10:35:15

标签: java regex

我有以下正则表达式:(["'])(\\\1|[^\1])+\1

显然无法编译,因为[^\1]是非法的。

是否可以否定匹配的群组?

1 个答案:

答案 0 :(得分:4)

您不能在正面或负面角色类中使用反向引用。

但是你可以使用否定lookahead assertions来实现你想要的东西:

(["'])(?:\\.|(?!\1).)*\1

<强>解释

(["'])    # Match and remember a quote.
(?:       # Either match...
 \\.      # an escaped character
|         # or
 (?!\1)   # (unless that character is identical to the quote character in \1)
 .        # any character
)*        # any number of times.
\1        # Match the corresponding quote.
相关问题