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

From CodeCodex

(Add Seed7 example)
(Ruby)
 
Line 1: Line 1:
 
==Implementations==  
 
==Implementations==  
 +
 
===Java===
 
===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.  
 
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  
 
So the regex expression to replace "\" to "\\" is  
<highlightsyntax language="java122">
+
<pre class="java">
 
  myString = myString.replaceAll("\\\\","\\\\\\\\");
 
  myString = myString.replaceAll("\\\\","\\\\\\\\");
</highlightsyntax>
+
</pre>
  
 
In Java 1.5 and later, you can just use
 
In Java 1.5 and later, you can just use
<highlightsyntax language="java122">
+
<pre class="java">
 
  myString = myString.replace("\\","\\\\");
 
  myString = myString.replace("\\","\\\\");
</highlightsyntax>
+
</pre>
 
which is short for
 
which is short for
<highlightsyntax language="java122">
+
<pre class="java">
 
  myString = myString.replaceAll(Pattern.quote("\\"),Matcher.quoteReplacement("\\\\"));
 
  myString = myString.replaceAll(Pattern.quote("\\"),Matcher.quoteReplacement("\\\\"));
</highlightsyntax>
+
</pre>
 +
 
 +
===Ruby===
 +
<pre class="ruby">
 +
myString = myString.gsub(/\\/){'\\\\'}
 +
</pre>
  
 
===Seed7===
 
===Seed7===
Line 21: Line 27:
 
</pre>
 
</pre>
  
 +
[[Category:String]]
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Ruby]]
 
[[Category:Seed7]]
 
[[Category:Seed7]]

Latest revision as of 17:58, 4 March 2011

Implementations[edit]

Java[edit]

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

Ruby[edit]

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

Seed7[edit]

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