我有字符串模式,如下所示:
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
有谁知道为什么会这样吗?
最佳答案
使用 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)。
关于Java 正则表达式检查包含网址的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22375917/