다음을 통해 공유


예제: 날짜 형식 변경

다음 코드 예제에서는 Regex.Replace 메서드를 사용하여 mm/dd/yy 형식의 날짜를 dd-mm-yy 형식의 날짜로 바꿉니다.

예제

Function MDYToDMY(input As String) As String
    Return Regex.Replace(input, _
        "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
        "${day}-${month}-${year}")
End Function
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 메서드를 호출하는 방법을 보여 줍니다.

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
        Return Regex.Replace(input, _
            "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
            "${day}-${month}-${year}")
    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.
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.

참고

정규식 패턴 \b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b는 다음 표에서와 같이 해석됩니다.

패턴

설명

\b

단어 경계에서 일치 항목 찾기를 시작합니다.

(?<month>\d{1,2})

하나 또는 두 개의 10진수를 찾습니다. 이 그룹은 month 캡처된 그룹입니다.

/

슬래시 표시를 찾습니다.

(?<day>\d{1,2})

하나 또는 두 개의 10진수를 찾습니다. 이 그룹은 day 캡처된 그룹입니다.

/

슬래시 표시를 찾습니다.

(?<year>\d{2,4})

두 개에서 네 개의 10진수를 찾습니다. 이 그룹은 year 캡처된 그룹입니다.

\b

단어 경계에서 일치 항목 찾기를 끝냅니다.

패턴 ${day}-${month}-${year}는 다음 표에서와 같이 바꾸기 문자열을 정의합니다.

패턴

설명

$(day)

day 캡처링 그룹에서 캡처한 문자열을 추가합니다.

-

하이픈을 추가합니다.

$(month)

month 캡처링 그룹에서 캡처한 문자열을 추가합니다.

-

하이픈을 추가합니다.

$(year)

year 캡처링 그룹에서 캡처한 문자열을 추가합니다.

참고 항목

개념

.NET Framework 정규식