What is Pattern.COMMENTS in Java?

Overview

The Pattern.COMMENTS flag is used to ignore whitespace and comments in evaluation of a string.

The CASE_INSENSITIVE field of the Pattern class is used for allowing whitespace and comments in the regex pattern.

Enabling this flag ignores the whitespaces and comments starting with # until the end of the lineEOL in the given regex string.

Examples of regex with whitespace and comments include:

  • (.*) # Matching everything
  • [a-zA-Z] # Matching English Alphabets

Syntax

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

The Pattern.compile method takes the regex and match flags as arguments. Ignoring comments while pattern matching can be achieved by passing Pattern.COMMENTS flag as the match flag.

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String string = "Hello EDUCATIVE,how aRe yOU? With educative you learn things easily";
Pattern pattern = Pattern.compile("educative # Looking for educative", Pattern.COMMENTS);
Matcher match = pattern.matcher(string);
System.out.println("Matched characters:");
while (match.find()) {
System.out.println(match.group());
}
}
}

Free Resources