Replacing a Java string (removing newlines, changing $ to \ $)

I have a line like this (the $ character is always surrounded by other characters):

 a$b c$d e$f 

I want my string method to put \ in front of $ and delete the lines:

 a\$bc\$de\$f 

I tried this but did not put the \ character:

  s=s.replaceAll("\n","").replaceAll("$", "\\$"); 
+6
source share
5 answers

$ is a reserved character in java Pattern s; it indicates the end of a line or the end of input.

You also need to avoid replacing ... thrice.

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

+5
source

Use the replace() method instead of replaceAll() . Since Michelle correctly points out, replaceAll() uses regular expressions that cause problems with the $ character, while replace() is a literal, which is quite enough for your case.

+8
source

Escape $ :

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

$ is the metacharacter of the first argument of the replaceAll method. This first argument is a regular expression. In terms of regex, $ means end of line or line.

Code example

 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 
+2
source

Your problem here is that '$' is a regular expression metacharacter. That is, it is of particular importance. In particular, "$" means "end of line".

Since you do not have metacharacters in your template, you can use String.replace() instead, which simply replaces literal strings.

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

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

If you want to match the actual "$", you need to escape the "$" in the template to make it literal "$".

 \$ 

Then you also need to avoid quoting '\' for Java, so you get:

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

However, '$' is still the 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",""); 
+2
source

S and \ are special characters:

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

All Articles