Pattern flags() method in Java with examples

JavaObject Oriented ProgrammingProgramming

The pattern class of java.regex package is a compiled representation of a regular expression.

The compile() method of this class accepts a string value representing a regular expression and returns a Pattern object, the following is the signature of this method.

static Pattern compile(String regex)

Another variant of this method accepts an integer value representing flags, following is the signature of the compile method with two parameters.

static Pattern compile(String regex, int flags)

The Pattern class provides various fields each representing a flag

S.NoField and Description
Matches two characters only if they are canonically equal.
Matches characters irrespective of case.
Allows whitespace and comments in pattern.
Enables dotall mode. Where the “.” Meta character matches all the characters including line terminators.
Enables literal parsing of the pattern. i.e. all the metacharacters and escape sequences in the input sequence are treated as literal characters.
Enables multiline mode i.e. the whole input sequence is treated as a single line.
Enables Unicode-aware case folding i.e. when used along with CASE_INSENSITIVE. if you search for Unicode characters using regular expressions Unicode characters of both cases will be matched.
Enables the Unicode version of Predefined character classes and POSIX character classes.
This flag enables Unix lines mode.

The flags() method of this class returns the flag used in the current pattern.


import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
   public static void main(String[] args) {
      Scanner sc = new Scanner(;
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your Date of birth: ");
      String dob = sc.nextLine();
      //Regular expression to accept date in MM-DD-YYY format
      String regex = "^(1[0-2]|0[1-9])/ # For Month\n" + "(3[01]|[12][0-9]|0[1-9])/ # For Date\n"
+ "[0-9]{4}$ # For Year";
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(dob);
      boolean result = matcher.matches();
      if(result) {
         System.out.println("Given date of birth is valid");
      } else {
         System.out.println("Given date of birth is not valid");
      System.out.println("Flag used: "+ pattern.flags());


Enter your name:
Enter your Date of birth:
Given date of birth is valid
Flag used: 4
Published on 20-Nov-2019 05:56:30