Share via


교체 구문

교체 구문은 조건적 일치를 허용하도록 정규식을 수정합니다. .NET Framework는 세 가지 교체 구문을 지원합니다.

  • |와 패턴 일치

  • (?(expression)yes|no)를 사용한 조건부 일치

  • 유효한 캡처된 그룹을 기반으로 조건부 일치

|와 패턴 일치

세로 막대를 사용할 수 있습니다(|) 일련의 패턴 중 하나와 일치하는 문자 | 문자는 각 패턴을 구분합니다.

긍정 문자 클래스와 마찬가지로 |많은 단일 문자 중 하나를 찾는 데 문자를 사용할 수 있습니다. 다음 예제에서는 긍정 문자 클래스 및/또는 패턴 일치를 모두 사용합니다 |문자열에서 단어 "gray" 또는 "grey"의 발생을 찾는 단어. 이 경우 | 문자는 더 자세한 정보인 정규식을 생성합니다.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Regular expression using character class.
      Dim pattern1 As String = "\bgr[ae]y\b"
      ' Regular expression using either/or.
      Dim pattern2 As String = "\bgr(a|e)y\b"

      Dim input As String = "The gray wolf blended in among the grey rocks."
      For Each match As Match In Regex.Matches(input, pattern1)
         Console.WriteLine("'{0}' found at position {1}", _
                           match.Value, match.Index)
      Next      
      Console.WriteLine()
      For Each match As Match In Regex.Matches(input, pattern2)
         Console.WriteLine("'{0}' found at position {1}", _
                           match.Value, match.Index)
      Next      
   End Sub
End Module
' The example displays the following output:
'       'gray' found at position 4
'       'grey' found at position 35
'       
'       'gray' found at position 4
'       'grey' found at position 35           
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Regular expression using character class.
      string pattern1 = @"\bgr[ae]y\b";
      // Regular expression using either/or.
      string pattern2 = @"\bgr(a|e)y\b";

      string input = "The gray wolf blended in among the grey rocks.";
      foreach (Match match in Regex.Matches(input, pattern1))
         Console.WriteLine("'{0}' found at position {1}", 
                           match.Value, match.Index);
      Console.WriteLine();
      foreach (Match match in Regex.Matches(input, pattern2))
         Console.WriteLine("'{0}' found at position {1}", 
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       'gray' found at position 4
//       'grey' found at position 35
//       
//       'gray' found at position 4
//       'grey' found at position 35           

사용하는 정규식 | 문자, \bgr(a|e)y\b은 다음 표와 같이 해석됩니다.

패턴

설명

\b

단어 경계를 시작합니다.

gr

문자 "gr"을 찾습니다.

(a|e)

"a" 또는 "e"를 찾습니다.

y\b

단어 경계에서 "y"를 찾습니다.

|문자는 문자 리터럴 및 정규식 언어 요소의 모든 조합을 포함할 수 있는 여러 문자 또는 하위 식을 수행하거나 일치시키는 데 사용할 수도 있습니다. (문자 클래스는 이 기능을 제공하지 않습니다.) 다음 예제에서는 사용합니다 |미국 등 추출할 문자 형식이 ddd-dd-dddd인 9자리 숫자의 사회 보장 번호(SSN) 또는 U.S. EIN(고용주 식별 번호), 형식이 dd-ddddddd인 9자리 숫자.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"
      Dim input As String = "01-9999999 020-333333 777-88-9999"
      Console.WriteLine("Matches for {0}:", pattern)
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
      Next   
   End Sub
End Module
' The example displays the following output:
'       Matches for \b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b:
'          01-9999999 at position 0
'          777-88-9999 at position 22
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b";
      string input = "01-9999999 020-333333 777-88-9999";
      Console.WriteLine("Matches for {0}:", pattern);
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index);
   }
}
// The example displays the following output:
//       Matches for \b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b:
//          01-9999999 at position 0
//          777-88-9999 at position 22

정규식 \b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b는 다음 표와 같이 해석됩니다.

패턴

설명

\b

단어 경계를 시작합니다.

(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})

다음 중 하나와 일치시킵니다: 두 10진수, 이어서 하이픈, 이어서 7개의 10진수 또는 세 10진수, 하이픈, 두 10진수, 하이픈, 4개의 10진수.

\d

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

맨 위로 이동

식을 사용한 조건부 일치

이 언어 요소는 초기 패턴에 일치시킬 수 있는지 여부에 따라 두 패턴 중 하나에 일치시키려고 시도합니다. 해당 구문은 다음과 같습니다.

(?(expression)yes|no)

식은 일치할 초기 패턴이고, yes는 식이 일치된 경우 일치할 패턴이며 no는 식이 일치되지 않은 경우 일치할 옵션 패턴입니다. 정규식 엔진은 식을 너비가 0인 어설션으로 처리합니다. 즉, 정규식 엔진은 식을 계산한 입력 스트림에서 앞으로 이동하지 않습니다. 따라서 이 구문은 다음과 동일한 결과를 가져옵니다.

(?(?=expression)yes|no)

(?=식)은 너비가 0인 어설션 구문입니다. 자세한 내용은 그룹화 구문을 참조하십시오. 정규식 엔진은 식을 앵커(너비가 0인 어설션)로 해석하기 때문에 식은 너비가 0인 어설션(자세한 내용은 정규식의 앵커 참조) 또는 예에도 포함되는 부분식이 되어야 합니다. 그렇지 않으면 예 yes 패턴을 대응시킬 수 없습니다.

참고참고

식 명명된 또는 번호 매기기 캡처링 그룹인 경우 교체 구문은 캡처 테스트로 해석됩니다. 자세한 내용은 다음 단원 유효한 캡처된 그룹을 기준으로 조건부 일치를 참조하십시오.즉, 정규식 엔진은 캡처된 부분 문자열을 일치시키려고 시도하지 않지만 대신 그룹의 존재 여부를 테스트합니다.

다음 예제는 |와 어느 하나/또는 패턴 일치 섹션에 나타나는 예제의 변형입니다. 조건부 일치를 사용하여 단어 경계 다음의 처음 세 문자에서 두 자리 다음에 하이픈이 있는지 여부를 확인합니다. 그럴 경우 미국을 일치시키려고 시도합니다. EIN(고용주 식별 번호). 그렇지 않은 경우 미국을 일치시키려고 시도합니다. SSN(사회 보장 번호)

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"
      Dim input As String = "01-9999999 020-333333 777-88-9999"
      Console.WriteLine("Matches for {0}:", pattern)
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
      Next   
   End Sub
End Module
' The example displays the following output:
'       Matches for \b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b:
'          01-9999999 at position 0
'          777-88-9999 at position 22
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b";
      string input = "01-9999999 020-333333 777-88-9999";
      Console.WriteLine("Matches for {0}:", pattern);
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index);
   }
}
// The example displays the following output:
//       Matches for \b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b:
//          01-9999999 at position 0
//          777-88-9999 at position 22

정규식 패턴 \b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b는 다음 표에서와 같이 해석됩니다.

패턴

설명

\b

단어 경계를 시작합니다.

(?(\d{2}-)

다음 세 문자를 두 자리 숫자와 하이픈으로 구성할지 여부를 결정합니다.

\d{2}-\d{7}

이전 패턴이 일치하는 경우, 두 자리 숫자, 하이픈, 일곱 개의 숫자를 일치시킵니다.

\d{3}-\d{2}-\d{4}

이전 패턴이 일치하지 않는 경우 세 10진수, 하이픈, 두 10진수, 다른 하이픈 및 네 10진수를 일치하십시오.

\b

단어 경계를 찾습니다.

맨 위로 이동

유효한 캡처된 그룹을 기반으로 조건부 일치

이 언어 요소는 지정된 캡처 그룹에 일치시킬 수 있는지 여부에 따라 두 패턴 중 하나에 일치시키려고 시도합니다. 해당 구문은 다음과 같습니다.

(?(이름)예|no)

또는

(?(번호)예|no)

name은 이름이고 number는 캡처링 그룹의 수이며, yes는 name 또는 number가 일치하는 경우 일치할 식이고 no는 일치하지 않는 경우 일치할 옵션 식입니다.

이름이 정규식 패턴에서 사용되는 캡처 그룹의 이름에 해당하지 않을 경우에는 교체 구문이 앞 단원에서 설명한 대로 해석됩니다. 일반적으로 식은 false를 평가합니다. 번호가 정규식 패턴에 사용되는 번호 매기기 캡처링 그룹에 해당하지 않는 경우 정규식 엔진이 ArgumentException를 throw합니다.

다음 예제는 |와 어느 하나/또는 패턴 일치 섹션에 나타나는 예제의 변형입니다. 두 자릿수와 하이픈으로 구성된 n2라는 캡처링 그룹을 사용합니다. 교체 구문은 이 캡처링 그룹이 입력 문자열에서 일치되었는지 여부를 테스트합니다. 있는 경우, 해당 교체 구문은 미국의 마지막 7 개의 자릿수를 일치시키려고 시도합니다. EIN(고용주 식별 번호). 그렇지 않은 경우 미국을 일치시키려고 시도합니다. SSN(사회 보장 번호)

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"
      Dim input As String = "01-9999999 020-333333 777-88-9999"
      Console.WriteLine("Matches for {0}:", pattern)
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
      Next   
   End Sub
End Module
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b";
      string input = "01-9999999 020-333333 777-88-9999";
      Console.WriteLine("Matches for {0}:", pattern);
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index);
   }
}
// The example displays the following output:
//       Matches for \b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b:
//          01-9999999 at position 0
//          777-88-9999 at position 22

정규식 패턴 \b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b는 다음 표에서와 같이 해석됩니다.

패턴

설명

\b

단어 경계를 시작합니다.

(?<n2>\d{2}-)*

두 개의 숫자 다음에 하이픈을 0개 또는 한 개 찾습니다. 이 n2 캡처링 그룹의 이름을 지정합니다.

(?(n2)

n2는 입력 문자열에서 일치 여부를 테스트합니다.

)\d{7}

n2가 일치하는 경우 일곱 개의 소수 자릿수를 일치시킵니다.

|\d{3}-\d{2}-\d{4}

n2가 일치하는 경우 세 10진수, 하이픈, 두 10진수, 다른 하이픈 및 네 10진수를 일치하십시오.

\b

단어 경계를 찾습니다.

명명된 그룹 대신 번호 매기기 그룹을 사용하는 이 예제의 변형은 다음 예제와 같습니다. 정규식 패턴은 \b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b입니다.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"
      Dim input As String = "01-9999999 020-333333 777-88-9999"
      Console.WriteLine("Matches for {0}:", pattern)
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index)
      Next   
   End Sub
End Module
' The example displays the following output:
'       Matches for \b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b:
'          01-9999999 at position 0
'          777-88-9999 at position 22
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b";
      string input = "01-9999999 020-333333 777-88-9999";
      Console.WriteLine("Matches for {0}:", pattern);
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("   {0} at position {1}", match.Value, match.Index);
   }
}
// The example display the following output:
//       Matches for \b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b:
//          01-9999999 at position 0
//          777-88-9999 at position 22

맨 위로 이동

참고 항목

개념

정규식 언어 요소