user3908406
user3908406

Reputation: 1796

How to escape $ in the value in replaceAll

For example

String updateValue(String value) {
return "PLACEHOLDER PLACEHOLDER".replaceAll("PLACEHOLDER", value);
}

updateValue("$3");

Expected output is $3 $3, but it will throw error java.lang.IndexOutOfBoundsException: No group 3 due to the char $. How to update the function updateValue so that it will output the expected result?

Here is what I have tried

String updateValue(String value) {
return "PLACEHOLDER PLACEHOLDER".replaceAll("PLACEHOLDER", value.replaceAll("\\$", "\\\\$"));
}

But it did not work, getting error Illegal group reference: group index is missing

Upvotes: 0

Views: 68

Answers (3)

DuncG
DuncG

Reputation: 15136

As your search string is not making use of regular expression you can use the standard search and replace call String.replace. Then the replace pattern does not need to be escaped:

"PLACEHOLDER PLACEHOLDER".replace("PLACEHOLDER", "$3");
==> "$3 $3"

Upvotes: 0

user3908406
user3908406

Reputation: 1796

String updateValue(String value) {
return "PLACEHOLDER PLACEHOLDER".replaceAll("PLACEHOLDER", value.replaceAll("\\$", "\\\\\\$"));
}

worked

Upvotes: 0

zoldxk
zoldxk

Reputation: 1

"PLACEHOLDER PLACEHOLDER".replaceAll("PLACEHOLDER", "\\$3")

Upvotes: 1

Related Questions