Java正则表达式:否定前瞻

时间:2012-06-20 18:02:16

标签: java regex negative-lookahead regex-lookarounds

我正在尝试制作两个匹配URI的正则表达式。这些URI的格式为:/foo/someVariableData/foo/someVariableData/bar/someOtherVariableData

我需要两个正则表达式。每个都需要匹配一个而不是另一个。

我最初提出的正则表达式是: <{1}}和/foo/.+

我认为第二个正则表达式很好。它只匹配第二个字符串。然而,第一个正则表达式匹配两者。所以,我开始玩(第一次)负向前瞻。我设计了正则表达式/foo/.+/bar/.+并设置了以下代码来测试它

/foo/.+(?!bar)

当然,他们都决心public static void main(String[] args) { String shouldWork = "/foo/abc123doremi"; String shouldntWork = "/foo/abc123doremi/bar/def456fasola"; String regex = "/foo/.+(?!bar)"; System.out.println("ShouldWork: " + shouldWork.matches(regex)); System.out.println("ShouldntWork: " + shouldntWork.matches(regex)); }

有人知道我做错了什么吗?我不需要使用否定前瞻,我只需要解决问题,我认为负向前瞻可能是一种方法。

谢谢,

1 个答案:

答案 0 :(得分:59)

尝试

String regex = "/foo/(?!.*bar).+";

或可能

String regex = "/foo/(?!.*\\bbar\\b).+";

以避免/foo/baz/crowbars这样的路径出现故障,我认为你确实希望匹配正则表达式。

说明:(没有Java字符串所需的双反斜杠)

/foo/ # Match "/foo/"
(?!   # Assert that it's impossible to match the following regex here:
 .*   #   any number of characters
 \b   #   followed by a word boundary
 bar  #   followed by "bar"
 \b   #   followed by a word boundary.
)     # End of lookahead assertion
.+    # Match one or more characters

\b,即“单词边界锚点”,匹配字母数字字符和非字母数字字符之间(或字符串的开头/结尾和alnum字符之间)的空格。因此,它在b之前或r中的"bar"之前匹配,但在w中的b"crowbar"之间无法匹配。

Protip:看看http://www.regular-expressions.info - 一个很棒的正则表达式教程。

相关问题