Reputation: 1796
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
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
Reputation: 1796
String updateValue(String value) {
return "PLACEHOLDER PLACEHOLDER".replaceAll("PLACEHOLDER", value.replaceAll("\\$", "\\\\\\$"));
}
worked
Upvotes: 0