java的java.util.regex包提供了各种类来查找字符序列中的特定模式。
该程序包的模式类是正则表达式的编译表示。此类的quote()方法接受字符串值,并返回与给定字符串匹配的模式字符串,即向给定字符串添加其他元字符和转义序列。无论如何,给定字符串的含义不受影响。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class QuoteExample { public static void main( String args[] ) { //读取字符串值 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); //编译正则表达式 Pattern pattern = Pattern.compile(regex); //检索Matcher对象 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
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 Nhooo"; //编译正则表达式 Pattern.compile(regex); regex = Pattern.quote(regex); System.out.println("pattern string: "+regex); //编译正则表达式 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