Java正则表达式:否定前瞻

Cod*_*y S 35 java regex negative-lookahead regex-lookarounds

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

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

我最初提出的正则表达式是: /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));
}
Run Code Online (Sandbox Code Playgroud)

当然,他们两个都决心true.

谁知道我做错了什么?我不需要使用Negative lookahead,我只需要解决问题,我认为负面的预测可能是一种方法.

谢谢,

Tim*_*ker 60

尝试

String regex = "/foo/(?!.*bar).+";
Run Code Online (Sandbox Code Playgroud)

或者可能

String regex = "/foo/(?!.*\\bbar\\b).+";
Run Code Online (Sandbox Code Playgroud)

避免路径上的失败/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
Run Code Online (Sandbox Code Playgroud)

\b,"单词边界锚",匹配字母数字字符和非字母数字字符之间(或字符串的开头/结尾和alnum字符之间)的空格.因此,之前匹配b或之后r"bar",但它不能之间不匹配w,并b"crowbar".

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