Pattern quote() method in Java with examples


The java.util.regex package of java provides various classes to find particular patterns in character sequences.

The pattern class of this package is a compiled representation of a regular expression. The quote() method of this class accepts a string value and returns a pattern string that would match the given string i.e. to the given string additional metacharacters and escape sequences are added. Anyway, the meaning of the given string is not affected.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      System.out.print("Enter the string to be searched: ");
      String regex = Pattern.quote(sc.nextLine());
      System.out.println("pattern string: "+regex);
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //retrieving the Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Enter input string
This is an example program demonstrating the quote() method
Enter the string to be searched: the
pattern string: \Qthe\E
Match found

Example 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      String input = "Hello how are you welcome to Tutorialspoint";
      //Compiling the regular expression
      Pattern.compile(regex);
      regex = Pattern.quote(regex);
      System.out.println("pattern string: "+regex);
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("The input string contains vowels");
      } else {
         System.out.println("The input string does not contain vowels");
      }
   }
}

Output

pattern string: \Q[aeiou]\E
The input string contains vowels

Updated on: 20-Nov-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements