我想製作兩個正則表達式,將匹配的URI。這些URI的格式爲:/foo/someVariableData
和/foo/someVariableData/bar/someOtherVariableData
Java的正則表達式:消極的lookahead
我需要兩個正則表達式。每個人都需要匹配一個而不是另一個。
我最初想出的正則表達式分別是: /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));
}
,當然,他們都決心true
。
有人知道我在做什麼錯嗎?我不一定需要使用負面預測,我只需要解決問題,我認爲負面預測可能是一種方法。
感謝,