public static void main(String[] args) throws Exception{
String str = "123ABC456";
String re = "7T$R";
//re= Matcher.quoteReplacement(re);
System.out.println(str.replaceFirst("ABC", re));
//System.out.println("[?]$yingyt".replaceFirst("[?]", "99"));
}
上述代码会直接报:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Matcher.java:713)
at java.util.regex.Matcher.replaceFirst(Matcher.java:861)
at java.lang.String.replaceFirst(String.java:2147)
at com.eshore.ppm.test.ws.ExcelTest2.main(ExcelTest2.java:267)
原因是:replaceFirst()方法没有对特殊方法进行处理。
处理方法:java.util.regex.Matcher.quoteReplacement()方法对被替换的字符串进行处理!