How to escape $ in java?

前端 未结 4 1435
别那么骄傲
别那么骄傲 2021-01-19 09:17

I am trying below code but getting error

String x = \"aaa XXX bbb\";
    String replace = \"XXX\";
    String y = \"xy$z\";
    String z=y.replaceAll(\"$\",          


        
4条回答
  •  臣服心动
    2021-01-19 09:50

    The reason for the error is that after the line:

    String z=y.replaceAll("$", "\\$");
    

    The value of z is: xy$z$ what you really want to do is:

    String x = "aaa XXX bbb";
    String replace = "XXX";
    String y = "xy\\$z";            
    x = x.replaceFirst(replace, y);
    System.out.println(x);
    

    which will output:

    aaa xy$z bbb
    

提交回复
热议问题