Edward
Edward

Reputation: 1377

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

Upvotes: 4

Views: 2864

Answers (3)

xdazz
xdazz

Reputation: 160843

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);

Upvotes: 3

Nir Alfasi
Nir Alfasi

Reputation: 53525

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

Upvotes: 1

João Silva
João Silva

Reputation: 91319

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.

Upvotes: 7

Related Questions