更新:2007 年 11 月
分组构造描述了正则表达式的子表达式,通常用于捕获输入字符串的子字符串。下表描述了正则表达式分组构造。
| 分组构造 | 说明 | 
|---|---|
| (子表达式) | 捕获匹配的子表达式(或非捕获组;有关更多信息,请参见正则表达式选项中的 ExplicitCapture 选项)。使用 () 的捕获基于左括号按顺序从 1 开始自动编号。捕获元素编号为零的第一个捕获是由整个正则表达式模式匹配的文本。 | 
| (?<name>子表达式) | 将匹配的子表达式捕获到一个组名称或编号名称中。用于 name 的字符串不得包含任何标点符号,并且不能以数字开头。可以使用单引号替代尖括号,例如 (?'name')。 | 
| (?<name1-name2>子表达式) | (平衡组定义。) 删除先前定义的 name2 组的定义,并在 name1 组中存储先前定义的 name2 组和当前组之间的间隔。如果未定义 name2 组,则匹配将回溯。由于删除 name2 的最后一个定义会显示 name2 的先前定义,因此该构造允许将 name2 组的捕获堆栈用作计数器,用于跟踪嵌套构造(如括号)。在此构造中,name1 是可选的。可以使用单引号替代尖括号,例如 (?'name1-name2')。 有关更多信息,请参见本主题中的示例。 | 
| (?:子表达式) | (非捕获组。) 不捕获由子表达式匹配的子字符串。 | 
| (?imnsx-imnsx:子表达式) | 应用或禁用子表达式中指定的选项。例如,(?i-s: ) 将打开不区分大小写并禁用单行模式。有关更多信息,请参见正则表达式选项。 | 
| (?=子表达式) | (零宽度正预测先行断言。) 仅当子表达式在此位置的右侧匹配时才继续匹配。例如,\w+(?=\d) 与后跟数字的单词匹配,而不与该数字匹配。此构造不会回溯。 | 
| (?!子表达式) | (零宽度负预测先行断言。) 仅当子表达式不在此位置的右侧匹配时才继续匹配。例如,\b(?!un)\w+\b 与不以 un 开头的单词匹配。 | 
| (?<=子表达式) | (零宽度正回顾后发断言。) 仅当子表达式在此位置的左侧匹配时才继续匹配。例如,(?<=19)99 与跟在 19 后面的 99 的实例匹配。此构造不会回溯。 | 
| (?<!子表达式) | (零宽度负回顾后发断言。) 仅当子表达式不在此位置的左侧匹配时才继续匹配。 | 
| (?>子表达式) | (非回溯子表达式(也称为“贪婪”子表达式)。) 该子表达式仅完全匹配一次,然后就不会逐段参与回溯了。(也就是说,该子表达式仅与可由该子表达式单独匹配的字符串匹配。) 默认情况下,如果匹配未成功,回溯会搜索其他可能的匹配。如果已知无法成功回溯,可以使用非回溯子表达式避免不必要的搜索,从而提高性能。 | 
命名捕获基于左括号按从左到右的顺序依次编号(与非命名捕获类似),但在对所有非命名捕获进行计数之后才开始对命名捕获编号。例如,模式 ((?<One>abc)\d+)?(?<Two>xyz)(.*) 按编号和名称产生下列捕获组。(编号为 0 的第一个捕获总是指整个模式)。
| 编号 | 名称 | 模式 | 
|---|---|---|
| 0 | 0(默认名称) | ((?<One>abc)\d+)?(?<Two>xyz)(.*) | 
| 1 | 1(默认名称) | ((?<One>abc)\d+) | 
| 2 | 2(默认名称) | (.*) | 
| 3 | 1 | (?<One>abc) | 
| 4 | 2 | (?<Two>xyz) | 
平衡组定义示例
下面的代码示例演示使用平衡组定义匹配输入字符串中的左右尖括号 (<>)。在该示例中,像使用堆栈那样使用 Open 组和 Close 组的捕获集合来跟踪尖括号配对:将所捕获的各左尖括号放入 Open 组的捕获集合中;将所捕获的各右尖括号放入 Close 组的捕获集合中;平衡组定义确保每个左尖括号均有一个匹配的右尖括号。
' 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>>"
*/