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

Метод quote() в шаблонах Java и примеры

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 a 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.

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[] ) {
      //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("строка шаблона: " + regex);
      // компиляция регулярного выражения
      Pattern pattern = Pattern.compile(regex);
      // поисковый запрос к объекту Matcher
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Найден совпадение");
      } else {
         System.out.println("Совпадение не найдено");
      }
   }
}

результат вывода

Введите вводную строку
Это примерная программа, демонстрирующая метод quote()
Введите строку для поиска: the
строка шаблона: \Qthe\E
Найден совпадение

пример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 w3codebox";
      // компиляция регулярного выражения
      Pattern.compile(regex);
      regex = Pattern.quote(regex);
      System.out.println("строка шаблона: " + regex);
      // компиляция регулярного выражения
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Вводная строка содержит гласные");
      } else {
         System.out.println("Вводная строка не содержит гласных");
      }
   }
}

результат вывода

строка шаблона: \Q[aeiou]\E
Вводная строка содержит гласные