Pattern類的quote(String)方法用於為作為參數傳遞給方法的指定String返回文字模式Pattern String。此方法產生一個等效於s的String,可用於創建Pattern。輸入序列中的元字符或轉義序列將沒有特殊含義。如果您對quote方法返回的值進行編譯,則會得到一個Pattern,該Pattern與您作為參數傳遞給method的文字字符串相匹配。\ Q和\ E標記該字符串的引號部分的開頭和結尾。
用法:
public static String quote(String s)
參數:此方法接受單個參數s,該參數s表示要被字符串化的字符串。
返回值:此方法返回String的文字字符串替換。
以下示例程序旨在說明quote()方法:
示例1:
// Java program to demonstrate
// Pattern.quote() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// create a REGEX String
String REGEX = "ee";
// create the string
// in which you want to search
String actualString
= "geeksforgeeks";
// create equivalent String for REGEX
String eqREGEX = Pattern.quote(REGEX);
// create a Pattern using eqREGEX
Pattern pattern = Pattern.compile(eqREGEX);
// get a matcher object
Matcher matcher = pattern.matcher(actualString);
// print values if match found
boolean matchfound = false;
while (matcher.find()) {
System.out.println("found the Regex in text:"
+ matcher.group()
+ " starting index:"
+ matcher.start()
+ " and ending index:"
+ matcher.end());
matchfound = true;
}
if (!matchfound) {
System.out.println("No match found for Regex.");
}
}
}
輸出:
found the Regex in text:ee starting index:1 and ending index:3 found the Regex in text:ee starting index:9 and ending index:11
示例2:
// Java program to demonstrate
// Pattern.quote() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// create a REGEX String
String REGEX = "welcome";
// create the string
// in which you want to search
String actualString
= "welcome to jungle";
// create equivalent String for REGEX
String eqREGEX = Pattern.quote(REGEX);
// create a Pattern using eqREGEX
Pattern pattern = Pattern.compile(eqREGEX);
// get a matcher object
Matcher matcher = pattern.matcher(actualString);
// print values if match found
boolean matchfound = false;
while (matcher.find()) {
System.out.println("match found");
matchfound = true;
}
if (!matchfound) {
System.out.println("No match found");
}
}
}
輸出:
match found
參考: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)
相關用法
- Java Pattern pattern()用法及代碼示例
- Java Pattern toString()用法及代碼示例
- Java Pattern splitAsStream()用法及代碼示例
- Java Pattern asPredicate()用法及代碼示例
- Java Matcher pattern()用法及代碼示例
- Java Pattern flags()用法及代碼示例
- Java Pattern matcher(CharSequence)用法及代碼示例
- Java Pattern compile(String)用法及代碼示例
- Java Pattern compile(String,int)用法及代碼示例
- Java Pattern split(CharSequence)用法及代碼示例
- Java Matcher usePattern(Pattern)用法及代碼示例
- Java Pattern split(CharSequence,int)用法及代碼示例
- Java Pattern matches(String ,CharSequence)用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Pattern quote(String) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。