replace `\\r` with `\r` in string

2019-07-29 07:38发布

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

4条回答
Animai°情兽
2楼-- · 2019-07-29 07:46

\ 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");
查看更多
放我归山
3楼-- · 2019-07-29 07:58

Character \r is a carriage return :)

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
查看更多
The star\"
4楼-- · 2019-07-29 08:08

You will have to escape each of the \ symbols.

Try:

test = test.replaceAll("\\\\r",  "\\r");
查看更多
一纸荒年 Trace。
5楼-- · 2019-07-29 08:12

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.

查看更多
登录 后发表回答