Why does replaceAll fail with “illegal group reference”?

前端 未结 8 1528
轻奢々
轻奢々 2020-12-01 09:56

I am in need to replace

\\\\\\s+\\\\$\\\\$ to $$

I used

String s = \"  $$\";
s = s.replaceAll(\"\\\\s+\\\\$\\\\$\",\"$$\"         


        
相关标签:
8条回答
  • 2020-12-01 10:57
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class HelloWorld{
    
     public static void main(String []args){
     String msg = "I have %s in my string";
    
        msg = msg.replaceFirst(Pattern.quote("%s"), Matcher.quoteReplacement("$"));
        System.out.println(msg);
     }
    

    }

    0 讨论(0)
  • 2020-12-01 10:58

    I had the same problem, so I end up implementing replace all with split.
    It solved the exception for me

    public static String replaceAll(String source, String key, String value){
        String[] split = source.split(Pattern.quote(key));
        StringBuilder builder = new StringBuilder();
        builder.append(split[0]);
        for (int i = 1; i < split.length; i++) {
            builder.append(value);
            builder.append(split[i]);
        }
        while (source.endsWith(key)) {
            builder.append(value);
            source = source.substring(0, source.length() - key.length());
        }
        return builder.toString();
    }
    
    0 讨论(0)
提交回复
热议问题