1

I am writing a program that only replaces double backslash, not single backslash.

I don't quite understand how this could be working in Java:

"\\".replaceAll("\\\\", "/")

The result is "/"

But I am expecting it should stay unchanged, since "\" is a single backslash character, the first \ is an escape character, right?

XL Zheng
  • 363
  • 1
  • 6
  • 14
  • 3
    Please also read the docs for the String `replaceAll()` method. https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#replaceAll(java.lang.String,java.lang.String) `replaceAll` takes a regex expression, so that means you have to quote the backslash with a backslash: "\\". But Java also requires you to quote backslashes, so each of those two backslashes needs to be quoted as well: "\\\\". If you use the `replace` method instead of `replaceAll`, then the extra quoting goes away (but you also don't get regex). – markspace Aug 17 '18 at 21:31

1 Answers1

1

Taking into account the escape characters of java strings the string would become \ (\\ -> \) while the regular expression becomes \\ (\\\\ -> \\).

For a regular expression \ is an escape character as well. Therefore the search pattern searches for \ (\\ -> \) and replaces that with the given /.

Joerg S
  • 4,730
  • 3
  • 24
  • 43