KnowDotNet NetRefactor

Using Regular Expressions - Replacing VB6 Replace

by Les Smith
Print this Article Discuss in Forums

The use of the VB6 Replace function should be replaced with RegEx.Replace for several reasons.  First, in VB.NET, the following code returns Nothing (i.e., an empty object) which if you are not expecting such a result, can raise an exception.

      Dim s As String = String.Empty
      
Dim s2 As String = Replace(s, Chr(9), "")
      
If s2.Length = 0 Then
         ' do something
      End If

You obviously would not code two lines like this, but the point is that if you pass an empty string to the Replace function, which is brought forward from VB6 only for compatibility purposes,  it will return an empty object, and testing the length of s2 in this case will raise an exception.

There are two alternates, in .NET, to using the VB6 Replace function.  The first is to use the String Replace method as shown below.  That is the simpliest method.  Some books have previously published that the string Replace method only supported single character replacement.  However, the string Replace method is overloaded and supports both Char and String parameters

      s = "$a b\ c d"
      
Dim exp As String = "\"
      s2 = s.Replace(s, exp)


The second method is to use the Regex.Replace method.  Although is is overkill for this simple example, there are uses for this methodology.  When using this function, since we do not know what characters are in the "exp" string, we must use RegEx.Escape to ensure that we handle characters that the Regular Expression Engine considers "escape characters", such as $,\, etc.  In the example shown below, the "exp" has a "\" in it, which is an escape character in Regular Expressions. Calling the Regex.Escape method, passing the "exp" string, before it is passed to the Replace method, automatically takes care of this excape character nuance of Regular Expressions.

      s = "a b\ c\ d"
      
Dim exp As String = "\"
      s2 = Regex.Replace(s, Regex.Escape(exp),
StringEmpty)

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing