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

quote() method in Java patterns and examples

javajava.util.regexThe package provides various classes to find specific patterns in character sequences.

The pattern class in this package is the compiled representation of regular expressions. This class'squote()The method accepts a string value and returns the pattern string that matches the given string, that is, adds other meta characters and escape sequences to the given string. In any case, the meaning of the given string is not affected.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      //Read 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);
      //Compile Regular Expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output Result

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

Example2

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 w"3codebox";
      //Compile Regular Expression
      Pattern.compile(regex);
      regex = Pattern.quote(regex);
      System.out.println("pattern string: "+regex);
      //Compile 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 Result

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