I need to convert all the occurrences of \\r
to \r
in string.
My attempt is following:
String test = "\\r New Value";
System.out.println(test);
test = test.replaceAll("\\r", "\r");
System.out.println("output: " + test);
Output:
\r New Value
output: \r New Value
\
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 usereplace()
instead. (You can of course technically usereplaceAll()
on simple strings as well by escaping the regex, but then you get into either having to usePattern.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:...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:and:
Character
\r
is a carriage return :)To print
\
use escape character\
Solution
Escape
\
with\
:)result
You will have to escape each of the
\
symbols.Try:
With
replaceAll
you would have to use.replaceAll("\\\\r", "\r");
because\
in regex you need to escape it so you need to use pass\\
to regex engine\
you need to write it as"\\"
.Clearer way would be using
replace("\\r", "\r");
which will automatically escape all regex metacharacters.