Pattern DOTALL field in Java with examples


The DOTALL field of the Pattern class Enables dotall mode. By default, the “.” Meta character in regular expressions matches all characters except line terminators.

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

Output

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

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

In other words when you use this as flag value to the compile() method, the “.” Meta character matches all the characters including line terminators.

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

Output

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

Updated on: 20-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements