Edgar Peixoto
Edgar Peixoto

Reputation: 559

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.

Upvotes: 1

Views: 781

Answers (2)

jlordo
jlordo

Reputation: 37813

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500665

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.)

Upvotes: 0

Related Questions