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

Example of LITERAL field in Java pattern

Enable text analysis of the pattern. Here, all characters (including escape sequences and metacharacters) have no special meaning and are treated as literal characters.

For example, usually, if you search for the regular expression "^This" in the given input text, it will match the wordThisStarting line.

Example

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 expressions start with MM-DD-YYY format accepts date
      String regex = "^This";
      //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);
   }
}

Output result

^This
Number of matches: 1

In text mode, the metacharacter "^" has no meaning, and the regular expression "^This" matches the exact word.

Example

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 expressions start with MM-DD-YYY format accepts date
      String regex = "^This";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
      System.out.println("Usually it is printed as: 
"+input);
      //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);
   }
}

Output result

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