This question already has an answer here:
In Java, the string
"\" represents a single backlash, the first backslash being an escape character. Thus
. 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
aa. 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
Note: I’m using Java SE 9.