2014-03-13 103 views
0

我有細繩紋,象下面這樣:包含字符串網絡ADDRES Java正則表達式檢查

String wwwPattern = "^(.*[a-zA-Z]+\\.[a-zA-Z]+\\.[a-zA-Z]+.*)$"; 

當我嘗試這種模式,以配合字符串我觀察到的是這樣的:

String string1 = "www.stackoverflow.com"; 
System.out.println(string1.matches(wwwPattern)); // print true, this is OK 

String string2 = "test www.stackoverflow.com test"; 
System.out.println(string2.matches(wwwPattern)); // print true, this is OK 

String string3 = "test \r\n www.stackoverflow.com test"; 
System.out.println(string3.matches(wwwPattern)); //print false 

不有人知道爲什麼發生這種情況

+4

你會不匹配有效的主機名,並與此正則表達式 – fge

+0

是的,我看到符合無效的主機名,但我想知道爲什麼模式失敗時字符串包含「\ r \ n」。問題出現在點和下一行字符中。 –

回答

4

使用Pattern.DOTALL標誌將換行符與.匹配。

要使用它內聯而不是int標誌,請使用(?s)

String pattern = "(?s)^(.*[a-zA-Z]+\\.[a-zA-Z]+\\.[a-zA-Z]+.*)$"; 
String input = "test \r\n www.stackoverflow.com test"; 
System.out.println(input.matches(pattern)); 

輸出

true 

另外我想在.*(第一和最後一個)後移動外括號,讓你在組1

匹配您的內容

類似於:"(?s)^.*([a-zA-Z]+\\.[a-zA-Z]+\\.[a-zA-Z]+).*$"

最後,看看fge的評論(+1)。

0

你的正則表達式開頭^與$結束,那麼:這就像說 UPDATE「行結束之前找到類似xxx.yyyy.zzz」:感謝您的意見

"test \r\n www.stackoverflow.com test" 

"test \r"(第一行)和"\n www.stackoverflow.com test"(第二線)

第一部分不匹配,因爲它不具有兩個點與線的端部之前之前和之後的字母,並.(正則表達式元字符)不匹配端除非you explicit that(將?s添加到您的正則表達式中)。

+0

但他有任何一方匹配任何一方的網址 – OGHaza

+0

@OGHaza我補充說明:它不符合行末 –

+1

是的,但其餘的答案是不正確的,除非適當的標誌是設置'(?m)','^ $'匹配輸入的開始和結束,而不是行。 – OGHaza

1

這裏可能有幾個問題。

首先,「。*」不會匹配換行符。其次,如果整個字符串與模式匹配,那麼使用String.matches()將只返回true。

你可能想嘗試使用模式和匹配器如此,如果你只是想在字符串中找到任何匹配。

String wwwPattern = ".*([a-zA-Z]+\\.[a-zA-Z]+\\.[a-zA-Z]+).*"; 
String stringTest = "test \r\n www.stackoverflow.com test"; 
Pattern p = Pattern.compile(wwwPattern); 
Matcher m = p.matcher(stringTest); 
System.out.println(m.find()); //print true 
相關問題