다음을 통해 공유


그룹화 구문

업데이트: 2007년 11월

그룹화 구문은 정규식의 부분식을 나타내며 대개 입력 문자열의 부분 문자열을 캡처합니다. 다음 표에서는 정규식 그룹화 구문에 대해 설명합니다.

그룹화 구문

설명

(subexpression)

Captures the matched subexpression (or noncapturing group; for more information, see the ExplicitCapture option in Regular Expression Options). ()를 사용하는 캡처는 여는 괄호의 순서에 따라 자동으로 1부터 번호가 지정됩니다. 캡처 요소 번호가 0인 첫 번째 캡처는 전체 정규식 패턴과 일치하는 텍스트입니다.

(?<name>subexpression)

일치하는 부분식을 그룹 이름 또는 번호 이름에 캡처합니다. name에 사용되는 문자열은 문장 부호를 포함할 수 없고 숫자로 시작할 수 없습니다. 꺾쇠괄호 대신 작은따옴표를 사용할 수 있습니다(예: (?'name')).

(?<name1-name2>subexpression)

균형 조정 그룹 정의입니다. 이 구문은 이전에 정의된 그룹 name2의 정의를 삭제하고 name2 그룹과 현재 그룹 사이의 간격을 name1 그룹에 저장합니다. name2 그룹을 정의하지 않은 경우에는 일치 항목이 역추적됩니다. name2의 마지막 정의를 삭제하면 name2의 이전 정의가 드러나므로 이 구문을 사용하면 name2 그룹에 대한 캡처 스택을 카운터로 사용하여 괄호와 같은 중첩 구문을 추적할 수 있습니다. 이 구문에서 name1은 선택적입니다. 꺾쇠괄호 대신 작은따옴표를 사용할 수 있습니다(예: (?'name1-name2')).

자세한 내용은 이 항목의 예제를 참조하십시오.

(?:subexpression)

비캡처 그룹입니다. 부분식과 일치하는 부분 문자열은 캡처하지 않습니다.

(?imnsx-imnsx:subexpression)

부분식에서 지정된 옵션을 적용하거나 사용하지 않도록 설정합니다. 예를 들어, (?i-s: )는 대/소문자를 구분하지 않도록 하고 단일 행 모드를 해제합니다. For more information, see Regular Expression Options.

(?=subexpression)

너비가 0인 긍정 우측 어설션입니다. 부분식이 오른쪽의 이 위치에서 일치하는 경우에만 계속 검색합니다. 예를 들어, \w+(?=\d)는 단어 및 그 다음의 숫자를 나타내며 이 경우 숫자는 일치하지 않습니다. 이 구문은 역추적되지 않습니다.

(?!subexpression)

너비가 0인 부정 우측 어설션입니다. 부분식이 오른쪽의 이 위치에서 일치하지 않는 경우에만 계속 검색합니다. 예를 들어, \b(?!un)\w+\b는 un으로 시작하지 않는 단어를 나타냅니다.

(?<=subexpression)

너비가 0인 긍정 좌측 어설션입니다. 부분식이 왼쪽의 이 위치에서 일치하는 경우에만 계속 검색합니다. 예를 들어, (?<=19)99는 19 다음에 나오는 99를 나타냅니다. 이 구문은 역추적되지 않습니다.

(?<!subexpression)

너비가 0인 부정 좌측 어설션입니다. 부분식이 왼쪽의 위치에서 일치하지 않는 경우에만 계속 검색합니다.

(?>subexpression)

역추적하지 않는 부분식(적극적 부분식)입니다. 부분식이 완전히 일치하면 역추적에 참여하지 않습니다. 즉, 부분식에서는 부분식 자체와 일치하는 문자열만 일치로 취급합니다.

기본적으로 일치하는 항목을 찾지 못하면 역추적을 통해 가능한 다른 항목이 검색됩니다. 역추적이 성공할 수 없는 경우 역추적하지 않는 부분식을 사용하여 불필요한 검색을 방지하고 성능을 향상시킬 수 있습니다.

명명된 캡처는 명명되지 않은 캡처와 마찬가지로 여는 괄호의 순서에 따라 왼쪽에서 오른쪽으로 번호가 매겨집니다. 그러나 명명된 캡처에 대한 번호는 명명되지 않은 모든 캡처 다음에 이어집니다. 예를 들어 패턴 ((?<One>abc)\d+)?(?<Two>xyz)(.*) 를 사용하면 번호 및 이름별로 다음과 같은 캡처 그룹이 생성됩니다. 첫 번째 캡처(0번)는 항상 전체 패턴을 나타냅니다.

번호

이름

패턴

0

0(기본 이름)

((?<One>abc)\d+)?(?<Two>xyz)(.*)

1

1(기본 이름)

((?<One>abc)\d+)

2

2(기본 이름)

(.*)

3

One

(?<One>abc)

4

Two

(?<Two>xyz)

균형 조정 그룹 정의 예제

다음 코드 예제에서는 균형 조정 그룹 정의를 사용하여 입력 문자열에서 왼쪽 꺾쇠괄호와 오른쪽 꺾쇠괄호(<>)를 찾는 방법을 보여 줍니다. 이 예제에서 열기 및 닫기 그룹의 캡처 컬렉션은 꺾쇠괄호의 일치 쌍을 추적하는 스택처럼 사용됩니다. 캡처된 각 왼쪽 꺾쇠괄호는 열기 그룹의 캡처 컬렉션으로 푸시되고 캡처된 각 오른쪽 꺾쇠괄호는 닫기 그룹의 캡처 컬렉션으로 푸시되며 균형 조정 그룹 정의는 각 왼쪽 꺾쇠괄호와 일치하는 오른쪽 꺾쇠괄호가 있도록 합니다.

' This code example demonstrates using the balancing group definition feature of 
' regular expressions to match balanced left angle bracket (<) and right angle 
' bracket (>) characters in a string. 

Imports System
Imports System.Text.RegularExpressions

Class Sample
    Public Shared Sub Main() 
'
'    The following expression matches all balanced left and right angle brackets(<>). 
'    The expression:
'    1)   Matches and discards zero or more non-angle bracket characters.
'    2)   Matches zero or more of:
'    2a)  One or more of:
'    2a1) A group named "Open" that matches a left angle bracket, followed by zero 
'         or more non-angle bracket characters. 
'         "Open" essentially counts the number of left angle brackets.
'    2b) One or more of:
'    2b1) A balancing group named "Close" that matches a right angle bracket, 
'         followed by zero or more non-angle bracket characters. 
'         "Close" essentially counts the number of right angle brackets.
'    3)   If the "Open" group contains an unaccounted for left angle bracket, the 
'        entire regular expression fails.
'
        Dim pattern As String = "^[^<>]*" & _
                                "(" + "((?'Open'<)[^<>]*)+" & _
                                "((?'Close-Open'>)[^<>]*)+" + ")*" & _
                                "(?(Open)(?!))$"
        Dim input As String = "<abc><mno<xyz>>"
'
        Dim m As Match = Regex.Match(input, pattern)
        If m.Success = True Then
            Console.WriteLine("Input: ""{0}"" " & vbCrLf & "Match: ""{1}""", _
                               input, m)
        Else
            Console.WriteLine("Match failed.")
        End If
    End Sub 'Main
End Class 'Sample 

'This code example produces the following results:
'
'Input: "<abc><mno<xyz>>"
'Match: "<abc><mno<xyz>>"
'
// This code example demonstrates using the balancing group definition feature of 
// regular expressions to match balanced left angle bracket (<) and right angle 
// bracket (>) characters in a string. 

using System;
using System.Text.RegularExpressions;

class Sample 
{
    public static void Main() 
    {
/*
    The following expression matches all balanced left and right angle brackets(<>). 
    The expression:
    1)   Matches and discards zero or more non-angle bracket characters.
    2)   Matches zero or more of:
    2a)  One or more of:
    2a1) A group named "Open" that matches a left angle bracket, followed by zero 
         or more non-angle bracket characters. 
         "Open" essentially counts the number of left angle brackets.
    2b) One or more of:
    2b1) A balancing group named "Close" that matches a right angle bracket, 
         followed by zero or more non-angle bracket characters. 
         "Close" essentially counts the number of right angle brackets.
    3)   If the "Open" group contains an unaccounted for left angle bracket, the 
        entire regular expression fails.
*/
    string pattern = "^[^<>]*" +
                     "(" + 
                       "((?'Open'<)[^<>]*)+" +
                       "((?'Close-Open'>)[^<>]*)+" +
                     ")*" +
                     "(?(Open)(?!))$";
    string input = "<abc><mno<xyz>>";
//
    Match m = Regex.Match(input, pattern);
    if (m.Success == true)
        Console.WriteLine("Input: \"{0}\" \nMatch: \"{1}\"", input, m);
    else
        Console.WriteLine("Match failed.");
    }
}

/*
This code example produces the following results:

Input: "<abc><mno<xyz>>"
Match: "<abc><mno<xyz>>"

*/

참고 항목

기타 리소스

정규식 언어 요소