Let’s consider the following code snippet in Java.
package escape;
final public class Main
{
public static void main(String[] args)
{
String s = "abc/xyz";
System.out.println(s.replaceAll("/", "\\\\"));
}
}
I just want to replace “/” with “\” in the above String abc/xyz and which is done and displays abc\xyz as expected but I couldn’t get why it requires back slashes four times. It looks like two back slashes are sufficient. Why such is not a case?
The reason is that
String.replaceAlluses regular expressions (and actually calls Matcher.replaceAll which does document this). In regular expressions you have to escape the ‘\’ also in string literals you have to escape the ‘\’. Your 4 slashes are two slashes in the java string. And thereby an escaped slash in the regular expression.