標籤:
樣本:更改日期格式
下面的程式碼範例使用 Regex.Replace 方法將 mm/dd/yy 格式的日期替換為 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}");}
下面的代碼示範如何在應用程式中調用 MDYToDMY 方法。
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模式 \b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b 的含義如下表所示。
|
模式 |
說明 |
|
\b |
在單詞邊界處開始匹配。 |
|
(?<month>\d{1,2}) |
匹配一個或兩個十進位數字。 這是 month 擷取的群組。 |
|
/ |
匹配斜線符號。 |
|
(?<day>\d{1,2}) |
匹配一個或兩個十進位數字。 這是 day 捕獲的組。 |
|
/ |
匹配斜線符號。 |
|
(?<year>\d{2,4}) |
匹配兩個到四個十進位數。 這是 year 捕獲的組。 |
|
\b |
在單詞邊界處結束匹配。 |
模式 ${day}-${month}-${year} 如下表所示定義了替換字串。
|
模式 |
說明 |
|
$(day) |
添加由 day 擷取的群組捕獲的字串。 |
|
- |
添加連字號。 |
|
$(month) |
添加由 month 擷取的群組捕獲的字串。 |
|
- |
添加連字號。 |
|
$(year) |
添加由 year 擷取的群組捕獲的字串。 |
.net 更改日期格式