【问题标题】:Java replaceAll / replace string with instances of dollar sign [duplicate]Java replaceAll /用美元符号实例替换字符串[重复]
【发布时间】:2012-09-21 13:45:51
【问题描述】:
public static String template = "$A$B"

public static void somemethod() {
         template.replaceAll(Matcher.quoteReplacement("$")+"A", "A");
         template.replaceAll(Matcher.quoteReplacement("$")+"B", "B");
             //throws java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3
         template.replaceAll("\\$A", "A");
         template.replaceAll("\\$B", "B");
             //the same behavior

         template.replace("$A", "A");
         template.replace("$B", "B");
             //template is still "$A$B"

}

我不明白。我使用了所有可以在互联网上找到的替换方法,包括我能找到的所有堆栈溢出。我什至试过\u0024!怎么了?

【问题讨论】:

    标签: java regex string replace dollar-sign


    【解决方案1】:

    替换不是就地完成(String 不能在 Java 中修改,它们是不可变的),而是保存在方法返回的新 String 中.您需要保存返回的String 引用以备不时之需,例如:

    template = template.replace("$B", "B");
    

    【讨论】:

    • 该死!我以前以正确的方式做过一百万次。我只是忘记了!谢谢!
    • @emha 如果你觉得这个答案有用,为什么不接受呢?
    【解决方案2】:

    字符串是不可变的。所以你需要将replaceAll的返回值赋值给一个新的String:

    String s = template.replaceAll("\\$A", "A");
    System.out.println(s);
    

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2013-01-11
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多