Reputation:
I need to escape the $
and therefore I need to replace all occurrences of $
with \$
So I wrote this method:
// String#replaceAll(String regex, String replacement)
public String escape$(String str) {
// the first \\$ to escape it in regular expression
// the second is a normal String so \\$ should mean \$
return str.replaceAll("\\$", "\\$");
}
String s = "$some$$text here";
System.out.println(escape$(s));
Before I submitted for production use, I thought hmmm let's test that even though I was certain it should work. And so I did...
Well you guessed it. It doesn't work! It returns the same thing!
// expected result of the above: \$some\$\$text here
// reality: $some$$text here
So why doesn't this work?!
Upvotes: 0
Views: 143
Reputation:
For Java regex, it's not just that you have to double escape a string for the language,
which always has to be done.
It's that you have to escape the dollar sign for the engine as well to
distinguish it from a capture variable.
The replace string is actually a template for a string formatter.
Always write the replacement text in it's raw form first.
The raw form is what is presented to the engine as a template for the formatter.
Raw: \\
+ \$
<- the engine parses this as \
+ $
(two separate literals)
Combined Raw: \\\$
Finally, for the language, just escape the escapes.
Stringed: "\\\\\\$"
Upvotes: 0
Reputation: 48404
You need to double-escape the replacement.
You probably don't want to use replaceAll
, as you'd actually need to double-double escape it, but you're not using regular expressions here.
Instead, you can just use replace
, which takes literals (and uses replaceAll
in the background, with quoted values - see Matcher#quoteReplacement).
Here are two examples:
System.out.println("$".replaceAll("\\$", "\\\\\\$"));
System.out.println("$".replace("$", "\\$"));
Output
\$
\$
Upvotes: 4