閱讀英文

共用方式為


正則表達式範例:變更日期格式

下列程式代碼範例使用 Regex.Replace 方法,將表單 mm/dd/yy 的日期取代為表單 dd-mm-yy

警告

使用 System.Text.RegularExpressions 來處理不受信任的輸入時,請設定逾時。 惡意使用者可以提供輸入給 RegularExpressions,導致 拒絕服務攻擊。 使用 RegularExpressions 的 ASP.NET Core 框架 API 會傳遞一個逾時設定。

範例

C#
static string MDYToDMY(string input)
{
   try {
      return Regex.Replace(input,
             @"\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b",
            "${day}-${month}-${year}", RegexOptions.None,
            TimeSpan.FromMilliseconds(150));
   }
   catch (RegexMatchTimeoutException) {
      return input;
   }
}

下列程式代碼示範如何在應用程式中呼叫 MDYToDMY 方法。

C#
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 {dateString} to {resultString}.");
   }

   static string MDYToDMY(string input)
   {
      try {
         return Regex.Replace(input,
                @"\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b",
               "${day}-${month}-${year}", RegexOptions.None,
               TimeSpan.FromMilliseconds(150));
      }
      catch (RegexMatchTimeoutException) {
         return input;
      }
   }
}
// The example displays the following output to the console if run on 8/21/2007:
//      Converted 08/21/2007 to 21-08-2007.

評論

正則表達式模式 \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 擷取群組所擷取的字串。

另請參閱


其他資源