Replace a "\" by "\\"

From CodeCodex

Revision as of 08:36, 24 July 2010 by (Talk)



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 <highlightsyntax language="java122">

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


In Java 1.5 and later, you can just use <highlightsyntax language="java122">

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

</highlightsyntax> which is short for <highlightsyntax language="java122">

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



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