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.
Example
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
static string MDYToDMY(string input)
{
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
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.
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class Class1
{
public static void Main()
{
string dateString = DateTime.Today.ToString("d",
DateTimeFormatInfo.InvariantInfo);
string resultString = MDYToDMY(dateString);
Console.WriteLine("Converted {0} to {1}.", dateString, resultString);
}
static string MDYToDMY(string input)
{
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
}
// The example displays the following output to the console if run on 8/21/2007:
// Converted 08/21/2007 to 21-08-2007.
Regex Replacement Pattern
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.