解决:java.lang.IllegalArgumentException: Illegal group reference

解决:java.lang.IllegalArgumentException: Illegal group reference

当使用String中的replaceAll方法时,如果替换的值中包含有$符号时,在进行替换操作时会出现如下错误。

public static void main(String[] args) {  
        String text = "123456";  
        String replacement = "two$two";  
        String resultString = text.replaceAll("2", replacement);  
        System.out.println(resultString);  
}

错误信息:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference  
    at java.util.regex.Matcher.appendReplacement(Matcher.java:713)  
    at java.util.regex.Matcher.replaceAll(Matcher.java:813)  
    at java.lang.String.replaceAll(String.java:2189)  
    at org.jerval.test.Main.main(Main.java:17)  

此时可以在进行替换操作前后分别对替换值中的$符号进行encode和decode操作,如下:

public static void main(String[] args) {  
        String text = "123456";  
        String replacement = "two$two";  
        replacement = replacement.replaceAll("\\$", "REPLACE_DOLLAR_SIGN");// encode replacement;  
String resultString = text.replaceAll("2", replacement); resultString = resultString.replaceAll("REPLACE_DOLLAR_SIGN", "\\$");// decode replacement;
System.out.println(resultString); }

结果:

1two$two3456  


(1)