Regular Expression \E Metacharacter in Java.

JavaObject Oriented ProgrammingProgramming

The subexpression/metacharacter “\E” ends the quoting begun with \Q. i.e. you can escape metacharacters in the regular expressions by placing them in between \Q and \E. For example, the expression [aeiou] matches the strings with vowel letters in it.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      }else {
         System.out.println("Match not occurred");
      }
   }
}

Output

Enter input string:
sample
Match occurred

But, if you use the same expression with in \Q and \E as \Q[aeiou]\E It matches the same sequence of characters “[aeiou]” in the given string. In short the meta characters loses their meaning and will be treated as normal characters.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "\\Q[aeiou]\\E";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

Output 1

Enter input string:
sample
Match not occurred

Output2

Enter input string:
The letters [aeiou] are vowels in English alphabet
Match occurred
raja
Published on 10-Jan-2020 15:40:53
Advertisements