Search code examples
javareplaceall

Java replace single backslach


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?


Solution

  • 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 /.