Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

regex

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("$", "\\$");
like image 996
AloneInTheDark Avatar asked Mar 11 '14 13:03

AloneInTheDark


People also ask

Does string trim remove newline?

Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

How do you replace a carriage return in a string in Java?

replaceAll("\\n", ""); s = s. replaceAll("\\r", ""); But this will remove all newlines. Note the double \ 's: so that the string that is passed to the regular expression parser is \n .

How do you replace all the symbols in a string in Java?

The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.


2 Answers

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.

like image 197
Warlord Avatar answered Sep 28 '22 09:09

Warlord


$ 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("\\$", "\\\\\\$")

like image 21
Mena Avatar answered Sep 28 '22 08:09

Mena