Export (0) Print
Expand All

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.

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.

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.

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.

Community Additions

ADD
Show:
© 2014 Microsoft