简体   繁体   中英

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

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.

\\ 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");

You will have to escape each of the \\ symbols.

Try:

test = test.replaceAll("\\\\r",  "\\r");

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM