Pattern flags() method in Java with examples


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
1CANON_EQ
Matches two characters only if they are canonically equal.
2CASE_INSENSITIVE
Matches characters irrespective of case.
3COMMENTS
Allows whitespace and comments in pattern.
4DOTALL
Enables dotall mode. Where the “.” Meta character matches all the characters including line terminators.
5LITERAL
Enables literal parsing of the pattern. i.e. all the metacharacters and escape sequences in the input sequence are treated as literal characters.
6MULTILINE
Enables multiline mode i.e. the whole input sequence is treated as a single line.
7UNICODE_CASE
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.
8UNICODE_CHARACTER_CLASS
Enables the Unicode version of Predefined character classes and POSIX character classes.
9UNIX_LINES
This flag enables Unix lines mode.

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

Example

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.in);
      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());
   }
}

Output

Enter your name:
Krishna
Enter your Date of birth:
09/26/1989
Given date of birth is valid
Flag used: 4

Updated on: 20-Nov-2019

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements