FAQ

Java

JSP

Servlet


Advertisement



How many backslashes?

In the previous FAQ: 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 near index 1

\

 ^

Note the definition of the replaceAll() method in the String class is:

public String replaceAll(String regex, String replacement)

   This method "replaces each substring of this string that matches the given regular expression with the given replacement."

We are dealing with regular expression pattern in Java String literal here.

For a backslash \
The pattern to match that would be \\
The String literal to create that pattern would have to have one backslash to escape each of the two backslashes: \\\\

Yes, four backslashes are for one!

So the correct way to do use the replaceAll() method to double up the backslashes are:

            String c1 = a1.replaceAll(“\\\\”, “\\\\\\\\”);   //output is “c:\\dev\\app\\source”

If you want to avoid the complex of  regex String literals, there is another option, use the replace method in the String class:

public String replace(char oldChar, char newChar)

   This method "returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."

This method deals with the chars, not regex, so:

            String d1 = a1.replace(“\\”, “\\\\”);   // is “c:\\dev\\app\\source”

Put all these together:

Public class Test {
     public static void main (String … argv) {

       String a1 = "c:\\dev\\app\\";

      System.out.println(a1);  // the output is “c:\dev\app\source”.

       //String b1 = a1.replaceAll("\\", "\\\\");  //runtime exception

     String c1 = a1.replaceAll(“\\\\”, “\\\\\\\\”);

     System.out.println(c1); // is “c:\\dev\\app\\source”   

     String d1 = a1.replace(“\\”, “\\\\”);

     System.out.println(d1); // is “c:\\dev\\app\\source”

     }

}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |