Replace a "\" by "\\"

From CodeCodex



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

 myString = myString.replaceAll("\\\\","\\\\\\\\");

In Java 1.5 and later, you can just use

 myString = myString.replace("\\","\\\\");

which is short for

 myString = myString.replaceAll(Pattern.quote("\\"),Matcher.quoteReplacement("\\\\"));


myString = myString.gsub(/\\/){'\\\\'}


  myString := replace(myString, "\\", "\\\\");