Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape $ in java?

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
like image 853
Edward Avatar asked Dec 20 '22 16:12

Edward


1 Answers

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.

like image 113
João Silva Avatar answered Jan 01 '23 12:01

João Silva