简体   繁体   中英

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

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

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

worked

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM