Share this page 

Replace a "\" by "\\"Tag(s): String/Number


It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\\\" in a regex expression.

So the regex expression to replace "\" to "\\" is

public class Test {
  public static void main(String[] args){
    String text = "\\\\server\\apps\\file.txt";
    System.out.println("original : " + text);
    System.out.println("converted : " + text.replaceAll("\\\\","\\\\\\\\"));
    /*
     output :
         original : \\server\apps\file.txt
         converted : \\\\server\\apps\\file.txt
     */
  }
}

See also this HowTo.