String's replaceAll() method and escape characters

java, regex, string

Solution

When replacing characters using regular expressions, you're allowed to use backreferences, such as `\1` to replace a using a grouping within the match.

This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.

Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)

Problem

The line ``` System.out.println("\\"); ``` prints a single back-slash (`\`). And ``` System.out.println("\\\\"); ``` prints double back-slashes (`\\`). Understood! But why in the following code: ``` class ReplaceTest { public static void main(String[] args) { String s = "hello.world"; s = s.replaceAll("\\.", "\\\\"); System.out.println(s); } } ``` is the output: ``` hello\world ``` instead of ``` hello\\world ``` After all, the `replaceAll()` method is replacing a dot (`\\.`) with (`\\\\`). Can someone please explain this?

Original source