Java 中的 Pattern quote() 方法示例
javaobject oriented programmingprogramming更新于 2024/5/7 1:16:17
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[] ) {
//读取字符串值
Scanner sc = new Scanner(System.in);
System.out.println("输入输入字符串");
String input = sc.nextLine();
System.out.print("输入要搜索的字符串:");
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("Match found");
} else {
System.out.println("Match not found");
}
}
}
输出
输入输入字符串 This is an example program demonstrating the quote() method 输入要搜索的字符串: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 Tutorialspoint";
//编译正则表达式
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("输入字符串包含元音");
} else {
System.out.println("输入字符串不包含元音");
}
}
}
输出
模式字符串:\Q[aeiou]\E 输入字符串包含元音
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

