Java 中的 Pattern DOTALL 字段(含示例)
Pattern 类的 DOTALL 字段启用 dotall 模式。默认情况下,正则表达式中的“.”元字符匹配除换行符之外的所有字符。
示例 1
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
在 dot all 模式中,它匹配所有字符,包括换行符。
换句话说,当你将此用作 compile() 方法的标志值时,“.”元字符将匹配所有字符,包括换行符。
示例 2
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
广告