String.matches()方法配置多行字符串的问题

shijiann 2012-02-09 11:36:14
有如下代码,为何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
...全文
213 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
爱摸鱼de老邪 2012-02-09
  • 打赏
  • 举报
回复
System.out.println("Multi line, matches(): " + file2.matches("(?s).*test.*"));
在默认的情况下 . 是不能匹配行结束符的(行结束符有 6 个,具体的可以看看 Pattern 的 API DOC)
(?s) 的意思表示 single-line 就是忽略换行符什么的,只看成单行进行处理。
shijiann 2012-02-09
  • 打赏
  • 举报
回复
对。谢谢still_rain。

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧