Java 中的 Pattern DOTALL 字段示例

javaobject oriented programmingprogramming更新于 2024/5/8 8:12:17

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.compile(regex);
      匹配器 matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
         System.out.print(matcher.group());
      }
      System.out.println();
      System.out.println("换行符数量:\n"+count);
   }
}

输出

这是一个示例,这是第二行
新行字符数:
36

在点全模式下,它匹配所有字符,包括行终止符。

换句话说,当您将其用作 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.compile(regex, Pattern.DOTALL);
      匹配器 matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
         System.out.print(matcher.group());
      }
      System.out.println();
      System.out.println("换行符数:\n"+count);
   }
}

输出

this is a sample
this is second line
换行符数:
37

相关文章


有用资源