简体   繁体   中英

Replace a String containing “$” with “\$” in Java

How can I do it? I made a research but I could not find a clear answer.I tried to use

pass = pass.replaceAll("$", "\\$");

but It does not work.

use

pass = pass.replace("$", "\\$");

It will also replace all occurrences. See JavaDoc .

If you prefer the hard way and want to use a regex, you need:

pass = pass.replaceAll("\\$", "\\\\\\$");

This can be simplified with Matcher.quoteReplacement() but still, only use replaceAll() when you need to replace something that matches a regular expression, and use replace() when you have to replace a literal sequence.

The problem is that String.replaceAll uses regular expressions, where both \\ and $ have special meanings. You don't want that as far as I can tell - you just want to replace the strings verbatim. As such, you should use String.replace :

pass = pass.replace("$", "\\$");

(Personally I think the fact that replaceAll uses regular expressions is a design mistake, but that's another matter.)

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