2012-06-20 28 views
26

我想製作兩個正則表達式,將匹配的URI。這些URI的格式爲:/foo/someVariableData/foo/someVariableData/bar/someOtherVariableDataJava的正則表達式:消極的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

有人知道我在做什麼錯嗎?我不一定需要使用負面預測,我只需要解決問題,我認爲負面預測可能是一種方法。

感謝,

回答

51

嘗試

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"之後的匹配,但它不匹配wb,"crowbar"

Protip:看看http://www.regular-expressions.info - 一個很好的正則表達式教程。