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
With replaceAll
you would have to use .replaceAll("\\\\r", "\r");
because
- to represent
\
in regex you need to escape it so you need to use pass \\
to regex engine
- but and to create string literal for single
\
you need to write it as "\\"
.
Clearer way would be using replace("\\r", "\r");
which will automatically escape all regex metacharacters.
You will have to escape each of the \
symbols.
Try:
test = test.replaceAll("\\\\r", "\\r");
\
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");
Character \r
is a carriage return :)
- What is the difference between \r and \n?
To print \
use escape character\
System.out.println("\\");
Solution
Escape \
with \
:)
public static void main(String[] args) {
String test = "\\\\r New Value";
System.out.println(test);
test = test.replaceAll("\\\\r", "\\r");
System.out.println("output: " + test);
}
result
\\r New Value
output: \r New Value