Elliott
Elliott

Reputation: 5609

replaceAll regular expression Replacing $

I am trying to replace all $ characters in a String expression like this

an example of a string with s$ and another with $s and here is the end.

so that the $ characters are surrounded by spaces.

I've tried string.replaceAll("$", " $ "); This results in a illegal Argument Exception.

When I try escaping the $ character like this:

string.replaceAll("\$", " $ ");  I get an invalid escape sequence error before I even build.  

When I try the following:

string.replaceAll("\\$", " $ ");  I get an illegal argument exception again.

Finally when I try this:

string.replaceAll("\\\\$", " $ ");   

It has no effect on the string at all. I know this is something stupid that I'm just not getting. Can anyone help here?

Upvotes: 0

Views: 1253

Answers (4)

axtavt
axtavt

Reputation: 242706

If you don't need parameters to be treated as regexps, use replace() instead of replaceAll() (it replaces all occurences of the first parameter as well, but doesn't treat it as regexp):

string.replace("$", " $ ");

Upvotes: 2

Chris
Chris

Reputation: 7855

You'll need two slashes on both sides

string.replaceAll("\\$", " \\$ ");

The first one escapes the second slash that will be passed to the regular expression. The expression is then "\$" which matches the $ sign. And you want to replace it with the same.

You have to escape the second parameter as well because allthough its not a regular expression the \ and the $ sign are a specical case here according to the documentation:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Upvotes: 5

martido
martido

Reputation: 383

The reason why you have to esacpe the $ sign in the replacement string is because the String#replaceAll() method uses Matcher#replaceAll() underneath the hood. Straight from the latter's Javadoc:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Upvotes: 0

Josh M.
Josh M.

Reputation: 27791

Try string.replaceAll("\\$", " \\$ ").

Upvotes: 0

Related Questions