In Java, the string "\\"
represents a single backlash, the first backslash being an escape character. Thus System.out.print("\\")
prints \
. However if "\\"
is given as the replacement argument in method replaceAll, as in "aba".replaceAll("b", "\\")
, the following exception is thrown: java.lang.IllegalArgumentException: character to be escaped is missing
.
Four slashes does the trick. Thus if one prints "aba".replaceAll("b", "\\\\")
the result is a\a
. But why is two slashes incorrect? Isn't the first slash the escaping slash, and the second slash the character to be escaped, just like in System.out.print("\\")
? Notice that only one escaping slash is sufficient for other replacement strings passed to replaceAll. E.g. printing "aba".replaceAll("b", "\t")
results in a a
.
Note: I'm using Java SE 9.
Edit: Some the questions suggested as duplicates are not duplicates. Please do not confuse this with the question of why four backslashes are needed in a regex to match a single backslash. This is not the same issue, as the second argument in replaceAll is obviously not a regex. You couldn't specify a replacement String with a regex because ultimately replacement needs to resolve to a literal String.