日期:2014-05-20  浏览次数:20765 次

String.matches()方法配置多行字符串的问题
有如下代码,为何file2.matches(".*test.*")输出false?多行字符串应该怎么匹配?

public class MyTest {
public static void main(String[] args) {
String file1 = "This is a test file.";
String file2 = "This is a test file. Test!\nThe second line.";
System.out.println(file2);
System.out.println("----------->");
System.out.println("Single line, matches(): " + file1.matches(".*test.*"));
System.out.println("Multi line, matches(): " + file2.matches(".*test.*")); //为何false?
System.out.println("Multi line, contains(): " + file2.contains("second"));
}
}
输出为:
C:\> java MyTest
This is a test file. Test!
The second line.
----------->
Single line, matches(): true
Multi line, matches(): false
Multi line, contains(): true

------解决方案--------------------
System.out.println("Multi line, matches(): " + file2.matches("(?s).*test.*"));
在默认的情况下 . 是不能匹配行结束符的(行结束符有 6 个,具体的可以看看 Pattern 的 API DOC)
(?s) 的意思表示 single-line 就是忽略换行符什么的,只看成单行进行处理。