Skip to main content

Posts

Showing posts with the label backslashes

How many backslashes?

In the previous Question: Which replace function works with regex? , We compare the different replace methods in the String class. Here we will focus on replacing backslashes inside a String. The path in Windows uses the backslashes between folder names.  For example, the path of my java source is "c:\dev\app\source".  Since backslash is a special character in Java String, if we want to put this path inside a Java String literal, we need to escape the backslashes, it will be      String a1 = "c:\\dev\\app\\source";       System.out.println(a1);  // the output is “c:\dev\app\source”. Now we want to change all the single backslashes to double backslashes, one may think this would work:             String b1 = a1.replaceAll("\\", "\\\\"); But instead you will get Runtime Exception: java.util.regex.PatternSyntaxException: Unexpected internal error ne...