Matcher quoteReplacement(String s) 方法在 Java 中带有示例
Matcher 类的 appendReplacement() 方法接受一个 StringBuffer 对象和一个 String(替换字符串)作为参数,并将输入数据附加到 StringBuffer 对象,使用替换字符串替换匹配的内容。
在内部,此方法从输入字符串中读取每个字符并附加字符串缓冲区,每当发生匹配时,它会将替换字符串附加到缓冲区中而不是替换字符串中匹配内容的一部分,并且从匹配子字符串的下一个位置继续。
如果在此方法中传递替换字符串时使用 “/” 或 “$”,则它们不会被视为常规字符并且会出现异常 −
示例 1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class QuoteReplacement { public static void main(String[] args) { String str = " <p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>"; //Regular expression to match contents of the bold tags String regex = "<b>(\S+)</b>"; System.out.println("Input string: \n"+str); //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(str); //Creating an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "sampledata$" ); //Matcher.quoteReplacement("Bo$ld/Data$")); } matcher.appendTail(sb); System.out.println("Contents of the StringBuffer: \n"+ sb.toString() ); } }
输出
Input string:<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference: group index is missing at java.util.regex.Matcher.appendReplacement(Unknown Source) at OCTOBER.matcher.QuoteReplacement.main(QuoteReplacement.java:18)
Matcher 类的 quote Replacement 方法接受字符串值并返回一个文字替换字符串。即,忽略给定字符串中的字符 / 和 $,并且结果可以用作 appendReplacement() 方法的参数。
示例 2
import java.util.regex.Matcher; import java.util.regex.Pattern; public class QuoteReplacement { public static void main(String[] args) { String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p>"; //Regular expression to match contents of the bold tags String regex = "<b>(\S+)</b>"; System.out.println("Input string: \n"+str); //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(str); //Creating an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, Matcher.quoteReplacement("Bo$ld/Data$")); } matcher.appendTail(sb); System.out.println("Contents of the StringBuffer: \n"+ sb.toString() ); } }
输出
Input string: <p>This <b>is</b> an <b>example</b> HTML <b>script</b>.</p> Contents of the StringBuffer: <p>This Bo$ld/Data$ an Bo$ld/Data$ HTML Bo$ld/Data$.</p>
示例 3
import java.util.regex.Matcher; import java.util.regex.Pattern; public class QuoteReplacementExample { public static void main(String[] args) { String input = "This is sample text"; String regex = "[#]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); //Creating an empty string buffer String str = Matcher.quoteReplacement("sampledata"); System.out.println(str); } }
输出
sampledata
广告