How to match the regex meta characters in java as literal characters.

JavaObject Oriented ProgrammingProgramming

The compile method of the patter class accepts two parameters −

  • A string value representing the regular expression.
  • An integer value a field of the Pattern class.

The filed LITERAL of the enables literal parsing of the pattern. i.e. all the regular expression metacharacters and escape sequences don’t have any special meaning they are treated as literal characters. Therefore, If you need to match the regular expression metacharacters as normal characters you need to pass this as a flag value to the compile() method along with the regular expression.

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]";
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
      //Creating 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);
   }
}

Output 1

Enter input data:
9848022338
Number of matches: 0

Output 2

Enter input data:
^[0-9]
^[0-9]
Number of matches: 1
raja
Published on 21-Nov-2019 12:37:10
Advertisements