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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。