English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to match regular expression metacharacters as literal characters in Java.

The compile method of the Pattern class accepts two parameters-

  • The string value representing the regular expression.

  • An integer value, which is a field of the Pattern class.

The field LITERAL in the Pattern class enables the literal parsing of the pattern. That is, all regular expression metacharacters and escape sequences have no special meaning and are treated as literal characters. Therefore, if you need to match regular expression metacharacters as regular characters, you need to pass them as a flag valuecompile()passed to the method along with regular expressions.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String[] args) {
      System.out.println("Enter input data: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^[0-9];
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
         System.out.println(matcher.group());
      }
      System.out.println("Number of matches: ");+count);
   }
}

Output1

Enter input data:
9848022338
Number of matches: 0

Output2

Enter input data:
^[0-9]
^[0-9]
Number of matches: 1