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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP