Java 中 Pattern quote() 方法附带示例


java 的 java.util.regex 包提供多种类,用于在字符序列中查找特定模式。

此包的 pattern 类是正则表达式的编译表示形式。此类的 quote() 方法接受一个字符串值并返回一个模式字符串,该模式字符串与给定的字符串匹配,即向给定的字符串添加额外的元字符和转义序列。不论如何,给定字符串的含义不受影响。

示例 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");
      }
   }
}

输出

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

示例 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");
      }
   }
}

输出

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

更新于: 2019-11-20

2K+ 次浏览

开启你的 职业 生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.