Java中的 Matcher quoteReplacement(String) 方法及示例
Matcher 类的quoteReplacement(String 字符串)方法用于获取作为参数传递的 String 的替换字符串字面量量。此字符串字面量充当替换方法的参数。因此,quoteReplacement() 方法充当替换方法中的中间体。
句法:
public static String quoteReplacement(String string)
参数:此方法接受一个参数字符串,该字符串是匹配器中要替换的字符串。
返回值:此方法返回一个字符串字面量,它是匹配器的替换字符串。
下面的示例说明了 Matcher.quoteReplacement() 方法:
示例 1:
// Java code to illustrate quoteReplacement() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "Geek";
// Create a pattern from regex
Pattern pattern = Pattern.compile(regex);
// Get the String to be matched
String
stringToBeMatched
= "GeeksForGeeks Geeks for For Geeks Geek";
// Create a matcher for the input String
Matcher matcher
= pattern
.matcher(stringToBeMatched);
// Get the String to be replaced
String stringToBeReplaced = "Geeks";
// Get the String literal
// using quoteReplacement() method
System.out.println(
matcher
.quoteReplacement(stringToBeReplaced));
}
}
输出:
Geeks
示例 2:
// Java code to illustrate quoteReplacement() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "FGF";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String
stringToBeMatched
= "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF";
// Create a matcher for the input String
Matcher matcher
= pattern.matcher(stringToBeMatched);
// Get the String to be replaced
String stringToBeReplaced = "GFG";
// Get the String literal
// using quoteReplacement() method
System.out.println(
matcher
.quoteReplacement(stringToBeReplaced));
System.out.println(
matcher
.replaceAll(
matcher
.quoteReplacement(
stringToBeReplaced)));
}
}
输出:
GFG
GGFGGGFGGGFGGGFGGFG GFG GFG GFG GFG
参考: Oracle 文档