AloneInTheDark
AloneInTheDark

Reputation: 938

Java string replacing (remove newlines, change $ to \$)

I have a string like that ($ character is always surrounded with other characters):

a$b
c$d
e$f

I want my string method to put a \ in front of $ and remove newlines:

a\$bc\$de\$f

I tried this but it doesn't put \ character:

 s=s.replaceAll("\n","").replaceAll("$", "\\$");

Upvotes: 6

Views: 215

Answers (5)

slim
slim

Reputation: 41223

Your issue here is that '$' is a regular expression metacharacter. That is, it has special meaning. Specifically, '$' means 'end of string'.

Since you don't have any metacharacters in your pattern, you can instead use String.replace(), which just replaces literal strings.

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

However, if you really want to use replaceAll() (for example if other parts of your pattern need to be metacharacters):

If you want to match an actual '$', you need to escape the '$' in the pattern to make it a literal '$'.

\$

Then you also need to escape the '\' for Java's quoting, so you end up with:

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

However, '$' is still a metacharacter in the second parameter, so we need more:

 s = s.replaceAll("\\$",Matcher.quoteReplacement("\\$"));

Together with your other replacement:

 s = s.replaceAll("\\$",Matcher.quoteReplacement("\\$")).replaceAll("\n","");

Upvotes: 2

Warlord
Warlord

Reputation: 2826

Use replace() method instead of replaceAll(). As Michelle correctly notes, replaceAll() uses regular expressions, that cause problems with $ character, while replace() is literal, which is quite sufficient for your case.

Upvotes: 8

Stephan
Stephan

Reputation: 43013

Escape $ like this:

s=s.replaceAll("\n","").replaceAll("\\$", "\\\\\\$");

$ is a metacharacter for the first argument of the replaceAllmethod. This first argument is a regular expression. From a regular expression point of view, $ means end of line or string.

Sample code

String s = "a$b\n" +
           "c$d\n" +
           "e$f\n";

s = s.replaceAll("\n", "").replaceAll("\\$", "\\\\\\$");

System.out.println(s);

Output

a\$bc\$de\$f

Upvotes: 2

Farvardin
Farvardin

Reputation: 5414

S and \ are special characters :

s = s.replaceAll("\n", "").replaceAll("\\$", "\\\\\\$");

Upvotes: 0

Mena
Mena

Reputation: 48404

$ is a reserved character in java Patterns, it indicates the end of line or end of input.

You also need to escape the replacement... thrice.

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

Upvotes: 5

Related Questions