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("$", "\\$");
Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
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 .
The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
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.
$
is a reserved character in java Pattern
s, it indicates the end of line or end of input.
You also need to escape the replacement... thrice.
Try replaceAll("\\$", "\\\\\\$")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With