# 規則運算式中的反向參考建構Backreference Constructs in Regular Expressions

.NET 會定義個別的語言項目，以參考編號和具名擷取群組。.NET defines separate language elements to refer to numbered and named capturing groups. 如需擷取群組的詳細資訊，請參閱群組建構For more information about capturing groups, see Grouping Constructs.

## 編號反向參考Numbered Backreferences

\ number\ number

• 運算式 \1\9 一律會解譯為反向參考，而不是八進位字碼。The expressions \1 through \9 are always interpreted as backreferences, and not as octal codes.

• 如果多位數運算式的第一個數字是 8 或 9 (例如 \80\91)，該運算式會解譯為常值。If the first digit of a multidigit expression is 8 or 9 (such as \80 or \91), the expression as interpreted as a literal.

• \10 到更大值的運算式會視為反向參考 (如果有對應至該數字的反向參考)，否則會解譯為八進位字碼。Expressions from \10 and greater are considered backreferences if there is a backreference corresponding to that number; otherwise, they are interpreted as octal codes.

• 如果規則運算式包含未定義之群組號碼的反向參考，便會發生剖析錯誤，而規則運算式引擎會擲回 ArgumentExceptionIf a regular expression contains a backreference to an undefined group number, a parsing error occurs, and the regular expression engine throws an ArgumentException.

(\w) 比對文字字元，並將其指派給第一個擷取群組。Match a word character and assign it to the first capturing group.
\1 比對與第一個擷取群組之值相同的下一個字元。Match the next character that is the same as the value of the first capturing group.
using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"(\w)\1";
string input = "trellis llama webbing dresser swagger";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("Found '{0}' at position {1}.",
match.Value, match.Index);
}
}
// The example displays the following output:
//       Found 'll' at position 3.
//       Found 'll' at position 8.
//       Found 'bb' at position 16.
//       Found 'ss' at position 25.
//       Found 'gg' at position 33.

Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim pattern As String = "(\w)\1"
Dim input As String = "trellis llama webbing dresser swagger"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("Found '{0}' at position {1}.", _
match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
'       Found 'll' at position 3.
'       Found 'll' at position 8.
'       Found 'bb' at position 16.
'       Found 'ss' at position 25.
'       Found 'gg' at position 33.


## 具名反向參考Named Backreferences

\k< name >\k< name >

\k' name '\k' name '

(?<char>\w) 比對字組字元，並將其指派給名為 char 的擷取群組。Match a word character and assign it to a capturing group named char.
\k<char> 比對下一個與 char 擷取群組值相同的字元。Match the next character that is the same as the value of the char capturing group.
using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"(?<char>\w)\k<char>";
string input = "trellis llama webbing dresser swagger";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("Found '{0}' at position {1}.",
match.Value, match.Index);
}
}
// The example displays the following output:
//       Found 'll' at position 3.
//       Found 'll' at position 8.
//       Found 'bb' at position 16.
//       Found 'ss' at position 25.
//       Found 'gg' at position 33.

Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim pattern As String = "(?<char>\w)\k<char>"
Dim input As String = "trellis llama webbing dresser swagger"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("Found '{0}' at position {1}.", _
match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
'       Found 'll' at position 3.
'       Found 'll' at position 8.
'       Found 'bb' at position 16.
'       Found 'ss' at position 25.
'       Found 'gg' at position 33.


## 具名的數值反向參考Named numeric backreferences

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"(?<2>\w)\k<2>";
string input = "trellis llama webbing dresser swagger";
foreach (Match match in Regex.Matches(input, pattern))
Console.WriteLine("Found '{0}' at position {1}.",
match.Value, match.Index);
}
}
// The example displays the following output:
//       Found 'll' at position 3.
//       Found 'll' at position 8.
//       Found 'bb' at position 16.
//       Found 'ss' at position 25.
//       Found 'gg' at position 33.

Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim pattern As String = "(?<2>\w)\k<2>"
Dim input As String = "trellis llama webbing dresser swagger"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("Found '{0}' at position {1}.", _
match.Value, match.Index)
Next
End Sub
End Module
' The example displays the following output:
'       Found 'll' at position 3.
'       Found 'll' at position 8.
'       Found 'bb' at position 16.
'       Found 'ss' at position 25.
'       Found 'gg' at position 33.


using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
Console.WriteLine(Regex.IsMatch("aa", @"(?<char>\w)\k<1>"));
// Displays "True".
}
}



Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Console.WriteLine(Regex.IsMatch("aa", "(?<char>\w)\k<1>"))
' Displays "True".
End Sub
End Module



using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
Console.WriteLine(Regex.IsMatch("aa", @"(?<2>\w)\k<1>"));
// Throws an ArgumentException.
}
}



Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Console.WriteLine(Regex.IsMatch("aa", "(?<2>\w)\k<1>"))
' Throws an ArgumentException.
End Sub
End Module



## 反向參考比對的項目What Backreferences Match

(?<1>a) 比對字元 "a"，並將結果指派給名為 1 的擷取群組。Match the character "a" and assign the result to the capturing group named 1.
(?<1>\1b)* 比對 0 或多次出現名為 1 和 "b" 之群組的情況，並將結果指派給名為 1 的擷取群組。Match zero or more occurrences of the group named 1 along with a "b", and assign the result to the capturing group named 1.
using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"(?<1>a)(?<1>\1b)*";
string input = "aababb";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine("Match: " + match.Value);
foreach (Group group in match.Groups)
Console.WriteLine("   Group: " + group.Value);
}
}
}
// The example displays the following output:
//          Group: aababb
//          Group: abb

Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim pattern As String = "(?<1>a)(?<1>\1b)*"
Dim input As String = "aababb"
For Each match As Match In Regex.Matches(input, pattern)
Console.WriteLine("Match: " + match.Value)
For Each group As Group In match.Groups
Console.WriteLIne("   Group: " + group.Value)
Next
Next
End Sub
End Module
' The example display the following output:
'          Group: aababb
'          Group: abb


1. 它會從該字串的開頭開始，並且成功地比對 "a" 與運算式 (?<1>a)It starts at the beginning of the string, and successfully matches "a" with the expression (?<1>a). 1 群組的值現在是 "a"。The value of the 1 group is now "a".

2. 它會前進到第二個字元，並且成功地比對字串 "ab" 與運算式 \1b，或是 "ab"。It advances to the second character, and successfully matches the string "ab" with the expression \1b, or "ab". 然後它會將結果 "ab" 指派給 \1It then assigns the result, "ab" to \1.

3. 它會前進到第四個字元。It advances to the fourth character. 運算式 (?<1>\1b)* 要比對零次以上，才算成功地比對字串 "abb" 與運算式 \1bThe expression (?<1>\1b)* is to be matched zero or more times, so it successfully matches the string "abb" with the expression \1b. 然後它會將結果 "abb" 指派回到 \1It assigns the result, "abb", back to \1.

\b 開始字邊界比對。Begin the match on a word boundary.
(\p{Lu}{2}) 比對兩個大寫字母。Match two uppercase letters. 這是第一個擷取群組。This is the first capturing group.
(\d{2})? 比對出現零次或一次的兩個十進位數字。Match zero or one occurrence of two decimal digits. 這是第二個擷取群組。This is the second capturing group.
(\p{Lu}{2}) 比對兩個大寫字母。Match two uppercase letters. 這是第三個擷取群組。This is the third capturing group.
\b 結束字邊界比對。End the match on a word boundary.

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b";
string[] inputs = { "AA22ZZ", "AABB" };
foreach (string input in inputs)
{
Match match = Regex.Match(input, pattern);
if (match.Success)
{
Console.WriteLine("Match in {0}: {1}", input, match.Value);
if (match.Groups.Count > 1)
{
for (int ctr = 1; ctr <= match.Groups.Count - 1; ctr++)
{
if (match.Groups[ctr].Success)
Console.WriteLine("Group {0}: {1}",
ctr, match.Groups[ctr].Value);
else
Console.WriteLine("Group {0}: <no match>", ctr);
}
}
}
Console.WriteLine();
}
}
}
// The example displays the following output:
//       Match in AA22ZZ: AA22ZZ
//       Group 1: AA
//       Group 2: 22
//       Group 3: ZZ
//
//       Match in AABB: AABB
//       Group 1: AA
//       Group 2: <no match>
//       Group 3: BB

Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim pattern As String = "\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"
Dim inputs() As String = { "AA22ZZ", "AABB" }
For Each input As String In inputs
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
Console.WriteLine("Match in {0}: {1}", input, match.Value)
If match.Groups.Count > 1 Then
For ctr As Integer = 1 To match.Groups.Count - 1
If match.Groups(ctr).Success Then
Console.WriteLine("Group {0}: {1}", _
ctr, match.Groups(ctr).Value)
Else
Console.WriteLine("Group {0}: <no match>", ctr)
End If
Next
End If
End If
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
'       Match in AA22ZZ: AA22ZZ
'       Group 1: AA
'       Group 2: 22
'       Group 3: ZZ
'
'       Match in AABB: AABB
'       Group 1: AA
'       Group 2: <no match>
'       Group 3: BB