\
is used for escaping in Java - so every time you actually want to match a backslash in a string, you need to write it twice.
In addition, and this is what most people seem to be missing - replaceAll()
takes a regex, and you just want to replace based on simple string substitution - so use replace()
instead. (You can of course technically use replaceAll()
on simple strings as well by escaping the regex, but then you get into either having to use Pattern.quote()
on the parameters, or writing 4 backslashes just to match one backslash, because it's a special character in regular expressions as well as Java!)
A common misconception is that replace()
just replaces the first instance, but this is not the case:
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
...the only difference is that it works for literals, not for regular expressions.
In this case you're inadvertently escaping r
, which produces a carriage return feed! So based on the above, to avoid this you actually want:
String test = "\\\\r New Value";
and:
test = test.replace("\\\\r", "\\r");