English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

DOTALL field example in Java pattern

The DOTALL field of the Pattern class enables dotall mode. By default, the meta-character "." in the regular expression matches all characters except line termination.

Example1

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);
   }
}

Output Result

this is a sample this is second line
Number of new line characters:
36

In dot all mode, it matches all characters, including line terminators.

In other words, when you use it ascompile()The flag value of the method, the ".” meta-character matches all characters, including line terminators.

Example2

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);
   }
}

Output Result

this is a sample
this is second line
Number of new line characters:
37