2013-03-25 42 views
-2

爲什麼在Java中的正則表達式庫中的EOL在下一命令EOL在Java中的正則表達式

Matcher matcher = Pattern.compile("[\\\\r\\\\n$]+").matcher(" where "); 
if (matcher.find()) 
{ 
// found reaction 
} 
+1

問題是什麼? – Keppil 2013-03-25 19:03:25

回答

5

這不是一個新行正則表達式中。您字面上與以下字符中的一個匹配1次或多次:\r,\,n$。在where中,有一個r,所以該模式在字符串中找到。

新行正則表達式是\r|\n|\r\n。在JAVA中,你需要轉義反斜槓,所以它將是\\r|\\n|\\r\\n

+0

什麼是EOL正則表達式? – John 2013-03-25 19:11:09

+0

@John看我的編輯。 – sp00m 2013-03-25 19:13:11

0

兩個問題:

  1. 正則表達式是不正確的,你只需要一個轉義序列。模式是\r\n,而不是\\r\\n。在Java中,你需要將它們轉義一次,所以模式是\\r\\n
  2. 您在(" where ")中搜索的字符串不包含任何回車+換行(只是\ r)。

這將找到一個回車+換行:

Matcher matcher = Pattern.compile("[\\r\\n$]+").matcher(" where \n"); 
if (matcher.find()){ 
    System.out.println("found"); 
}