Pattern LITERAL field in Java with examples


Enables literal parsing of the pattern. In this, all the characters including escape sequences and, meta-characters don’t have any special meaning they are treated as literal characters.

For example, normally if you search for the regular expression “^This” in the given input text it matches the lines starting with the word "This".

Example 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
   public static void main(String[] args) {
      String input = "This is the first line\n"
         + "This is the second line\n"
         + "^This is the third line";
      //Regular expression to accept date in MM-DD-YYY format
      String regex = "^This";
      //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

^This
Number of matches: 1 

In literal mode, the metacharacter “^” has no meaning and the regular expression “^This” matches the exact word.

Example 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
   public static void main(String[] args) {
      String input = "This is the first line\n"
         + "This is the second line\n"
         + "^This is the third line";
      //Regular expression to accept date in MM-DD-YYY format
      String regex = "^This";
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex,Pattern.LITERAL);
      System.out.println("Usually it is printed as: \n"+input);
      //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

Usually it is printed as: 
This is the first line
This is the second line
^This is the third line
^This
Number of matches: 1

Updated on: 05-Dec-2023

837 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements