How to enable multiple flags while pattern matching in Java

Overview

Many times, developers need to use multiple flags during pattern matching in Java. Java has a collection of flags that may be used to override certain defaults. The way the Java regex engine matches the pattern is affected by these settings.

For example, Pattern.CASE_INSENSITIVE and Pattern.COMMENTS need to be used for case-insensitive matching, and the regex contains comments that have to be ignored during the execution stage.

To know more about the Pattern class, refer to What is a regex.Pattern class in Java?

How to enable multiple flags during pattern matching

The Bitwise OR operator (|) can enable multiple flags while creating an instance of the Pattern class.

The overloaded static method compile(String regex, int flags) is used to set the flags at the time of java.util.regex.Pattern creation. The flag’s parameter is a bit mask that can include any number of flags in the Pattern class.

The syntax is as follows:

Pattern pattern = Pattern.compile(regex, flag_1 | flag_2);

Any number of flags can be enabled using the bitwise OR operator.

For example, in the expression below, we enable two different flags.

Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS | Pattern.CASE_INSENSITIVE);

Code

In the code given below, we enable the following two flags using the bitwise OR operator.

  • Pattern.COMMENTS
  • Pattern.CASE_INSENSITIVE
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
public static void main(String[] args){
String string = "Hello eDUcatIVE";
String regex = "educative # Matching the keyword educative";
// Define a pattern object with the relevant flags enabled and regular expression
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS | Pattern.CASE_INSENSITIVE);
// Match the string with the pattern
Matcher match = pattern.matcher(string);
System.out.println("Matched characters:");
// Print the matched characters
while (match.find()) {
System.out.println(match.group());
}
}
}

Free Resources