2012-07-21 53 views
3

我希望这个Java正则表达式在两个括号之间的匹配所有文本:显示与评论​​如何正确使用此Java正则表达式的负向预测?

%(.*?)\((.*?)(?!\\)\) 

%(.*?)  # match all text that immediately follows a '%' 
\(   # match a literal left-paren 
(.*?)  # match all text that immediately follows the left-paren 
(?!\\)  # negative lookahead for right-paren: if not preceded by slash... 
\)   # match a literal right-paren 

但它没有(如本test证明)。

此输入:

%foo(%bar \(%baz\)) hello world)

我预计%bar \(%baz\)但看到%bar \(%baz\(没有逃脱右括号)。我在猜测,我对负向预测构造的使用在某种程度上是不正确的。有人可以用我的正则表达式来解释这个问题吗?谢谢。

回答

1

你甚至不需要四处看看。只需使用否定字符类[^\\]并将其包括在组中:

%(.*?)\((.*?[^\\])\) 
1

我想出了这个问题。当我实际上需要负面后视时,我使用负向预测。

正则表达式应该已经:

%(.*?)  # match all text that immediately follows a '%' 
\(   # match a literal left-paren 
(.*?)  # match all text that immediately follows the left-paren 
(?<!\\)  # negative lookbehind for right-paren: if not preceded by slash... 
\)   # match a literal right-paren 

此修复程序证明here