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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With