Difference between revisions of "Replace a "\" by "\\""

From CodeCodex

(Java)
(Add Seed7 example)
Line 15: Line 15:
 
  myString = myString.replaceAll(Pattern.quote("\\"),Matcher.quoteReplacement("\\\\"));
 
  myString = myString.replaceAll(Pattern.quote("\\"),Matcher.quoteReplacement("\\\\"));
 
</highlightsyntax>
 
</highlightsyntax>
 +
 +
===Seed7===
 +
<pre>
 +
  myString := replace(myString, "\\", "\\\\");
 +
</pre>
  
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Seed7]]

Revision as of 08:36, 24 July 2010

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