2012-08-02 82 views
1

我有下面的代碼段:的Java .matches()不匹配

String myString; 
boolean myResult; 

myString = "First\nSecond\nThird\nFourth"; 
myResult = myString.matches("First.*"); 
myResult = myString.matches(".*First.*"); 
myResult = myString.matches(".*Second.*"); 
myResult = myString.matches("First\nSecond\nThird\nFourth"); 

最後一個返回true,其餘全部都是假的......

我雖然上​​述所有表達式將返回true。另外我需要找到以「First」開頭的字符串,我認爲第一個.matches()會覆蓋它,但它不會。它應該是什麼樣子?

回答

2

的點通過結束行默認匹配字符沒有,但如果你的前綴字符串的正則表達式用(S?),那麼它就會匹配他們。這將啓用DOTALL匹配標誌。

+0

當場。謝謝! – tom 2012-08-02 13:09:59

2

。*可能不匹配\ n

用您的上一個匹配模式替換\ n。並看看會發生什麼。

1

documentation

。任何字符(可能會或可能不會匹配行結束符)

1

你可以嘗試從字面上指定\ n \ r:

myResult = myString.matches("First(.|[\n\r])*")