Pattern类的DOTALL字段启用dotall模式。默认情况下,“。” 正则表达式中的元字符与除行终止符外的所有字符匹配。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class DOTALL_Example { public static void main( String args[] ) { String regex = "."; String input = "this is a sample \nthis is second line"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); int count =0; while(matcher.find()) { count++; System.out.print(matcher.group()); } System.out.println(); System.out.println("Number of new line characters: \n"+count); } }
输出结果
this is a sample this is second line Number of new line characters: 36
在点所有模式下,它与所有字符匹配,包括行终止符。
换句话说,当您将其用作compile()
方法的标志值时,“。” 元字符匹配所有字符,包括行终止符。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class DOTALL_Example { public static void main( String args[] ) { String regex = "."; String input = "this is a sample \nthis is second line"; Pattern pattern = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.print(matcher.group()); } System.out.println(); System.out.println("Number of new line characters: \n"+count); } }
输出结果
this is a sample this is second line Number of new line characters: 37