Example: changing the date format
The following code example uses a Regex. the Replace method replaces thedate in mm/dd/yy format with the date dd-mm-yy format.
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 to call the Mdytodmy method in an application .
usingSystem;usingSystem.Globalization;usingSystem.Text.RegularExpressions; Public classclass1{ Public Static voidMain () {stringdatestring = DateTime.Today.ToString ("D", Datetimeformatinfo.invariantinfo); stringResultstring =mdytodmy (datestring); Console.WriteLine ("converted {0} to {1}.", datestring, resultstring); } Static stringMdytodmy (stringinput) { returnregex.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.
Comments
The meaning of the regular expression pattern \b (? <month>\d{1,2})/(? <day>\d{1,2})/(? <year>\d{2,4}) \b is as shown in the following table.
Mode |
Description |
\b |
Start a match at the word boundary. |
(? <month>\d{1,2}) |
Matches one or two decimal digits. This is the month capture group. |
/ |
Matches a left slash. |
(? <day>\d{1,2}) |
Matches one or two decimal digits. This is the group that is captured by day. |
/ |
Matches a left slash. |
(? <year>\d{2,4}) |
Match two to four decimal digits. This is the group captured by year. |
\b |
Ends the match at the word boundary. |
Pattern ${day}-${month}-${year} The replacement string is defined as shown in the following table.
Mode |
Description |
$ (day) |
Adds a string captured by the day capture group. |
- |
Add hyphens. |
$ (month) |
Adds a string captured by the month capture group. |
- |
Add hyphens. |
$ (year) |
Adds a string captured by the year capture group. |
. Net Change Date format