Replace a "\" by "\\"

From CodeCodex

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

Implementations

Java

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("\\\\","\\\\\\\\");

</highlightsyntax>

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("\\\\"));

</highlightsyntax>

Seed7

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