This documentation is archived and is not being maintained.

Example: Changing Date Formats

The following code example uses the Regex.Replace method to replace dates of the form mm/dd/yy with dates of the form dd-mm-yy.

Function MDYToDMY(input As String) As String 
    Return Regex.Replace(input, _
        "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
        "${day}-${month}-${year}")
End Function

The following code shows how the MDYToDMY method can be called in an application.

Imports System.Globalization
Imports System.Text.RegularExpressions

Module DateFormatReplacement
   Public Sub Main()
      Dim dateString As String = Date.Today.ToString("d", _
                                           DateTimeFormatInfo.InvariantInfo)
      Dim resultString As String = MDYToDMY(dateString)
      Console.WriteLine("Converted {0} to {1}.", dateString, resultString)
   End Sub 

    Function MDYToDMY(input As String) As String 
        Return Regex.Replace(input, _
            "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
            "${day}-${month}-${year}")
    End Function 
End Module 
' The example displays the following output to the console if run on 8/21/2007: 
'      Converted 08/21/2007 to 21-08-2007.

This example demonstrates the use of named backreferences within the replacement pattern for Replace(String, String, String). Here, the replacement expression ${day} inserts the substring captured by the group (?<day>…).

The Replace(String, String, String) function is one of several static functions that enable you to use regular expression operations without creating an explicit regular expression object.

Show: