正規表現の例: 日付形式の変更

次のコード例では、Regex.Replace メソッドを使用して、フォーム mm//yy の日付を dd-mm-yy 形式の日付に置き換えます。

Warning

信頼されていない入力で System.Text.RegularExpressions を無制限に使用すると、アプリケーションが サービス拒否攻撃の対象になる可能性があります。 信頼されていない入力で.NET正規表現を安全に使用する方法については、.NETの正規表現のベスト プラクティスを参照してください。

Example

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;
   }
}
Function MDYToDMY(input As String) As String
    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 e As RegexMatchTimeoutException
        Return input
    End Try
End Function

次のコードは、アプリケーションで 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 {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.
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
        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 e As RegexMatchTimeoutException
            Return input
        End Try
    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.

コメント

この正規表現パターン \b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b の解釈を次の表に示します。

Pattern 説明
\b ワード境界から照合を開始する。
(?<month>\d{1,2}) 1 桁または 2 桁の 10 進数。 これは、キャプチャされたグループ month です。
/ スラッシュ記号に一致させます。
(?<day>\d{1,2}) 1 桁または 2 桁の 10 進数。 これは、キャプチャされたグループ day です。
/ スラッシュ記号に一致させます。
(?<year>\d{2,4}) 2桁から4桁の10進数字に一致します。 これは、キャプチャされたグループ year です。
\b ワード境界で照合を終了します。

パターン ${day}-${month}-${year} は、次の表に示すように置換文字列を定義します。

Pattern 説明
$(day) day キャプチャ グループによってキャプチャされた文字列を追加します。
- ハイフンを追加します。
$(month) month キャプチャ グループによってキャプチャされた文字列を追加します。
- ハイフンを追加します。
$(year) year キャプチャ グループによってキャプチャされた文字列を追加します。

こちらも参照ください