How to escape $ in java?

2020-04-10 03:45发布

I am trying below code but getting error

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

Error

Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
    at java.util.regex.Matcher.appendReplacement(Unknown Source)
    at java.util.regex.Matcher.replaceFirst(Unknown Source)
    at java.lang.String.replaceFirst(Unknown Source)
    at Test.main(Test.java:10)

I want result as

aaa xy$z bbb

4条回答
劳资没心,怎么记你
2楼-- · 2020-04-10 04:27

The problem id due to replaceFirst The value of String z=y.replaceAll("$", "\\$"); is xy$z$

Replaces the first substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceFirst(repl)

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string;

查看更多
对你真心纯属浪费
3楼-- · 2020-04-10 04:29

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
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-04-10 04:32

If the replacement string includes a dollar sign or a backslash character, you should use

Matcher.quoteReplacement()

So change

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

to

String z = Matcher.quoteReplacement(y);
查看更多
手持菜刀,她持情操
5楼-- · 2020-04-10 04:38

Use replace() instead, which doesn't use regular expressions, since you don't need them at all:

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

This will print aaa xy$z bbb, as expected.

查看更多
登录 后发表回答