扫码一下
查看教程更方便
Regex类 quoteReplacement() 方法返回指定字符串的字面替换字符串。这个方法返回一个字符串,就像传递给Matcher类的 appendReplacement 方法一个字面字符串一样工作。
public static String quoteReplacement(String s)
s - 要文字化的字符串。
文字字符串替换。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherDemo { private static String REGEX = "dog"; private static String INPUT = "The dog says meow " + "All dogs say meow."; private static String REPLACE = "cat$"; public static void main(String[] args) { Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); try{ //Below line will throw exception INPUT = matcher.replaceAll(REPLACE); } catch(Exception e){ System.out.println("Exception: "+ e.getMessage()); } INPUT = matcher.replaceAll(matcher.quoteReplacement(REPLACE)); System.out.println(INPUT); } }
上面示例编译运行结果如下
Exception: Illegal group reference: group index is missing
The cat$ says meow All cat$s say meow.