規則運算式物件模型The Regular Expression Object Model

本主題說明用來處理 .NET 規則運算式的物件模型。This topic describes the object model used in working with .NET regular expressions. 它包含以下各節:It contains the following sections:

規則運算式引擎The Regular Expression Engine

.NET 的規則運算式引擎會以 Regex 類別表示。The regular expression engine in .NET is represented by the Regex class. 規則運算式引擎負責剖析和編譯規則運算式,以及執行規則運算式模式與輸入字串的比對作業。The regular expression engine is responsible for parsing and compiling a regular expression, and for performing operations that match the regular expression pattern with an input string. 引擎是 .NET 規則運算式物件模型的中心元件。The engine is the central component in the .NET regular expression object model.

規則運算式引擎有兩種使用方式:You can use the regular expression engine in either of two ways:

  • 呼叫 Regex 類別的靜態方法。By calling the static methods of the Regex class. 方法參數包括輸入字串和規則運算式模式。The method parameters include the input string and the regular expression pattern. 規則運算式引擎會快取靜態方法呼叫中所使用的規則運算式,因此重複呼叫使用相同規則運算式的靜態規則運算式方法,可提供相對較佳的效能。The regular expression engine caches regular expressions that are used in static method calls, so repeated calls to static regular expression methods that use the same regular expression offer relatively good performance.

  • 傳遞規則運算式到類別建構函式,以具現化 Regex 物件。By instantiating a Regex object, by passing a regular expression to the class constructor. 在此案例中,Regex 物件不可變 (唯讀),並代表與單一規則運算式緊密結合的規則運算式引擎。In this case, the Regex object is immutable (read-only) and represents a regular expression engine that is tightly coupled with a single regular expression. 由於未快取 Regex 執行個體所使用的規則運算式,因此您不應該以相同的規則運算式將 Regex 物件具現化多次。Because regular expressions used by Regex instances are not cached, you should not instantiate a Regex object multiple times with the same regular expression.

您可以呼叫 Regex 類別的方法來執行下列作業:You can call the methods of the Regex class to perform the following operations:

  • 判定字串是否符合規則運算式模式。Determine whether a string matches a regular expression pattern.

  • 擷取單一相符項目或第一個相符項目。Extract a single match or the first match.

  • 擷取所有相符項目。Extract all matches.

  • 取代相符的子字串。Replace a matched substring.

  • 將單一字串分割成字串陣列。Split a single string into an array of strings.

下面各節將會說明這些作業。These operations are described in the following sections.

比對規則運算式模式Matching a Regular Expression Pattern

如果字串符合模式,Regex.IsMatch 方法會傳回 true,如果不符合,則傳回 falseThe Regex.IsMatch method returns true if the string matches the pattern, or false if it does not. IsMatch 方法常用來驗證字串輸入。The IsMatch method is often used to validate string input. 例如,下列程式碼可確保字串符合美國境內有效的社會安全號碼。For example, the following code ensures that a string matches a valid social security number in the United States.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] values = { "111-22-3333", "111-2-3333"};
      string pattern = @"^\d{3}-\d{2}-\d{4}$";
      foreach (string value in values) {
         if (Regex.IsMatch(value, pattern))
            Console.WriteLine("{0} is a valid SSN.", value);
         else   
            Console.WriteLine("{0}: Invalid", value);
      }
   }
}
// The example displays the following output:
//       111-22-3333 is a valid SSN.
//       111-2-3333: Invalid
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim values() As String = { "111-22-3333", "111-2-3333"}
      Dim pattern As String = "^\d{3}-\d{2}-\d{4}$"
      For Each value As String In values
         If Regex.IsMatch(value, pattern) Then
            Console.WriteLine("{0} is a valid SSN.", value)
         Else   
            Console.WriteLine("{0}: Invalid", value)
         End If   
      Next
   End Sub
End Module
' The example displays the following output:
'       111-22-3333 is a valid SSN.
'       111-2-3333: Invalid

規則運算式模式 ^\d{3}-\d{2}-\d{4}$ 的解譯方式如下表所示。The regular expression pattern ^\d{3}-\d{2}-\d{4}$ is interpreted as shown in the following table.

模式Pattern 說明Description
^ 比對輸入字串的開頭。Match the beginning of the input string.
\d{3} 比對三個十進位數字。Match three decimal digits.
- 比對連字號。Match a hyphen.
\d{2} 比對兩個十進位數字。Match two decimal digits.
- 比對連字號。Match a hyphen.
\d{4} 比對四個十進位數字。Match four decimal digits.
$ 比對輸入字串的結尾。Match the end of the input string.

擷取單一相符項目或第一個相符項目Extracting a Single Match or the First Match

Regex.Match 方法會傳回 Match 物件,其中包含符合規則運算式模式之第一個子字串的相關資訊。The Regex.Match method returns a Match object that contains information about the first substring that matches a regular expression pattern. 如果 Match.Success 屬性傳回 true,指出已找到相符項目,您就可以呼叫 Match.NextMatch 方法來擷取後續相符項目的相關資訊。If the Match.Success property returns true, indicating that a match was found, you can retrieve information about subsequent matches by calling the Match.NextMatch method. 這些方法呼叫可以一直持續到 Match.Success 屬性傳回 falseThese method calls can continue until the Match.Success property returns false. 例如,下列程式碼會使用 Regex.Match(String, String) 方法來尋找字串中第一次出現的重複文字。For example, the following code uses the Regex.Match(String, String) method to find the first occurrence of a duplicated word in a string. 然後會呼叫 Match.NextMatch 方法來尋找所出現的任何其他重複文字。It then calls the Match.NextMatch method to find any additional occurrences. 此範例會在每次方法呼叫之後檢查 Match.Success 屬性,以判定目前比對是否成功,以及後面是否應該接著呼叫 Match.NextMatch 方法。The example examines the Match.Success property after each method call to determine whether the current match was successful and whether a call to the Match.NextMatch method should follow.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle."; 
      string pattern = @"\b(\w+)\W+(\1)\b";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("Duplicate '{0}' found at position {1}.",  
                           match.Groups[1].Value, match.Groups[2].Index);
         match = match.NextMatch();
      }                       
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is a a farm that that raises dairy cattle." 
      Dim pattern As String = "\b(\w+)\W+(\1)\b"
      Dim match As Match = Regex.Match(input, pattern)
      Do While match.Success
         Console.WriteLine("Duplicate '{0}' found at position {1}.", _ 
                           match.Groups(1).Value, match.Groups(2).Index)
         match = match.NextMatch()
      Loop                       
   End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.

規則運算式模式 \b(\w+)\W+(\1)\b 的解譯方式如下表所示。The regular expression pattern \b(\w+)\W+(\1)\b is interpreted as shown in the following table.

模式Pattern 說明Description
\b 開始字邊界比對。Begin the match on a word boundary.
(\w+) 比對一個或多個文字字元。Match one or more word characters. 這是第一個擷取群組。This is the first capturing group.
\W+ 比對一或多個非文字字元。Match one or more non-word characters.
(\1) 比對第一個擷取的字串。Match the first captured string. 這是第二個擷取群組。This is the second capturing group.
\b 結束字邊界比對。End the match on a word boundary.

擷取所有相符項目Extracting All Matches

Regex.Matches 方法會傳回 MatchCollection 物件,其中包含規則運算式引擎在輸入字串中找到之所有相符項目的相關資訊。The Regex.Matches method returns a MatchCollection object that contains information about all matches that the regular expression engine found in the input string. 例如,您可以將上一個範例重寫為呼叫 Matches 方法,而不是 MatchNextMatch 方法。For example, the previous example could be rewritten to call the Matches method instead of the Match and NextMatch methods.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle."; 
      string pattern = @"\b(\w+)\W+(\1)\b";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("Duplicate '{0}' found at position {1}.",  
                           match.Groups[1].Value, match.Groups[2].Index);
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is a a farm that that raises dairy cattle." 
      Dim pattern As String = "\b(\w+)\W+(\1)\b"
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("Duplicate '{0}' found at position {1}.", _ 
                           match.Groups(1).Value, match.Groups(2).Index)
      Next                       
   End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.

取代相符的子字串Replacing a Matched Substring

Regex.Replace 方法會將符合規則運算式模式的每個子字串,取代為指定的字串或規則運算式模式,並傳回含有取代項目的整個輸入字串。The Regex.Replace method replaces each substring that matches the regular expression pattern with a specified string or regular expression pattern, and returns the entire input string with replacements. 例如,下列程式碼會在字串中的十進位數字前面加上美國貨幣符號。For example, the following code adds a U.S. currency symbol before a decimal number in a string.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+\.\d{2}\b";
      string replacement = "$$$&"; 
      string input = "Total Cost: 103.64";
      Console.WriteLine(Regex.Replace(input, pattern, replacement));     
   }
}
// The example displays the following output:
//       Total Cost: $103.64
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\d+\.\d{2}\b"
      Dim replacement As String = "$$$&" 
      Dim input As String = "Total Cost: 103.64"
      Console.WriteLine(Regex.Replace(input, pattern, replacement))     
   End Sub
End Module
' The example displays the following output:
'       Total Cost: $103.64

規則運算式模式 \b\d+\.\d{2}\b 的解譯方式如下表所示。The regular expression pattern \b\d+\.\d{2}\b is interpreted as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\d+ 比對一個或多個十進位數字。Match one or more decimal digits.
\. 比對句點。Match a period.
\d{2} 比對兩個十進位數字。Match two decimal digits.
\b 結束字緣比對。End the match at a word boundary.

取代模式 $$$& 的解譯方式如下表所示。The replacement pattern $$$& is interpreted as shown in the following table.

模式Pattern 取代字串Replacement string
$$ 貨幣符號 ($) 字元。The dollar sign ($) character.
$& 整個相符子字串。The entire matched substring.

將單一字串分割成字串陣列Splitting a Single String into an Array of Strings

Regex.Split 方法會在規則運算式比對所定義的位置分割輸入字串。The Regex.Split method splits the input string at the positions defined by a regular expression match. 例如,下列程式碼會將編號清單中的項目放在字串陣列中。For example, the following code places the items in a numbered list into a string array.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea";
      string pattern = @"\b\d{1,2}\.\s";
      foreach (string item in Regex.Split(input, pattern))
      {
         if (! String.IsNullOrEmpty(item))
            Console.WriteLine(item);
      }      
   }
}
// The example displays the following output:
//       Eggs
//       Bread
//       Milk
//       Coffee
//       Tea
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea"
      Dim pattern As String = "\b\d{1,2}\.\s"
      For Each item As String In Regex.Split(input, pattern)
         If Not String.IsNullOrEmpty(item) Then
            Console.WriteLine(item)
         End If
      Next      
   End Sub
End Module
' The example displays the following output:
'       Eggs
'       Bread
'       Milk
'       Coffee
'       Tea

規則運算式模式 \b\d{1,2}\.\s 的解譯方式如下表所示。The regular expression pattern \b\d{1,2}\.\s is interpreted as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\d{1,2} 比對一個或兩個十進位數字。Match one or two decimal digits.
\. 比對句點。Match a period.
\s 比對空白字元。Match a white-space character.

MatchCollection 和 Match 物件The MatchCollection and Match Objects

Regex 方法會傳回兩個屬於規則運算式物件模型的物件:MatchCollection 物件和 Match 物件。Regex methods return two objects that are part of the regular expression object model: the MatchCollection object, and the Match object.

比對集合The Match Collection

Regex.Matches 方法會傳回 MatchCollection 物件,其中包含 Match 物件,這些物件代表規則運算式引擎找到的所有相符項目,並按照其於輸入字串中出現的順序排列。The Regex.Matches method returns a MatchCollection object that contains Match objects that represent all the matches that the regular expression engine found, in the order in which they occur in the input string. 如果沒有相符項目,該方法會傳回 MatchCollection 物件,但不含成員。If there are no matches, the method returns a MatchCollection object with no members. MatchCollection.Item[Int32] 屬性可讓您依索引存取集合的個別成員,從零到 MatchCollection.Count 屬性的值減一。The MatchCollection.Item[Int32] property lets you access individual members of the collection by index, from zero to one less than the value of the MatchCollection.Count property. Item[Int32] 是集合的索引子 (在 C# 中) 和預設屬性 (在 Visual Basic 中)。Item[Int32] is the collection's indexer (in C#) and default property (in Visual Basic).

依預設,呼叫 Regex.Matches 方法時會使用延遲評估來填入 MatchCollection 物件。By default, the call to the Regex.Matches method uses lazy evaluation to populate the MatchCollection object. 若要存取需要完整填入集合的屬性,例如 MatchCollection.CountMatchCollection.Item[Int32] 屬性,可能會導致效能傷害。Access to properties that require a fully populated collection, such as the MatchCollection.Count and MatchCollection.Item[Int32] properties, may involve a performance penalty. 因此,建議您使用 IEnumerator 方法傳回的 MatchCollection.GetEnumerator 物件來存取集合。As a result, we recommend that you access the collection by using the IEnumerator object that is returned by the MatchCollection.GetEnumerator method. 個別語言會提供包裝集合之 IEnumerator 介面的建構 (例如 Visual Basic 中的 For Each,以及 C# 中的 foreach)。Individual languages provide constructs, such as For Each in Visual Basic and foreach in C#, that wrap the collection's IEnumerator interface.

下列範例使用 Regex.Matches(String) 方法,以在輸入字串中找到的所有相符項目來填入 MatchCollection 物件。The following example uses the Regex.Matches(String) method to populate a MatchCollection object with all the matches found in an input string. 此範例會列舉集合、將相符項目複製到字串陣列,並記錄整數陣列中的字元位置。The example enumerates the collection, copies the matches to a string array, and records the character positions in an integer array.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
       MatchCollection matches;
       List<string> results = new List<string>();
       List<int> matchposition = new List<int>();
   
       // Create a new Regex object and define the regular expression.
       Regex r = new Regex("abc");
       // Use the Matches method to find all matches in the input string.
       matches = r.Matches("123abc4abcd");
       // Enumerate the collection to retrieve all matches and positions.
       foreach (Match match in matches)
       {
          // Add the match string to the string array.
           results.Add(match.Value);
           // Record the character position where the match was found.
           matchposition.Add(match.Index);
       }
       // List the results.
       for (int ctr = 0; ctr < results.Count; ctr++)
         Console.WriteLine("'{0}' found at position {1}.", 
                           results[ctr], matchposition[ctr]);  
   }
}
// The example displays the following output:
//       'abc' found at position 3.
//       'abc' found at position 7.
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
       Dim matches As MatchCollection
       Dim results As New List(Of String)
       Dim matchposition As New List(Of Integer)
   
       ' Create a new Regex object and define the regular expression.
       Dim r As New Regex("abc")
       ' Use the Matches method to find all matches in the input string.
       matches = r.Matches("123abc4abcd")
       ' Enumerate the collection to retrieve all matches and positions.
       For Each match As Match In matches
          ' Add the match string to the string array.
           results.Add(match.Value)
           ' Record the character position where the match was found.
           matchposition.Add(match.Index)
       Next
       ' List the results.
       For ctr As Integer = 0 To results.Count - 1
         Console.WriteLine("'{0}' found at position {1}.", _
                           results(ctr), matchposition(ctr))  
       Next
   End Sub
End Module
' The example displays the following output:
'       'abc' found at position 3.
'       'abc' found at position 7.

比對The Match

Match 類別代表單一規則運算式比對的結果。The Match class represents the result of a single regular expression match. 您可以用兩個方式來存取 Match 物件:You can access Match objects in two ways:

  • MatchCollection 方法傳回的 Regex.Matches 物件中擷取。By retrieving them from the MatchCollection object that is returned by the Regex.Matches method. 若要擷取個別 Match 物件,請使用 foreach (在 C# 中) 或 For Each...Next (在 Visual Basic 中) 的建構來逐一查看集合,或是使用 MatchCollection.Item[Int32] 屬性來依據索引或名稱擷取特定的 Match 物件。To retrieve individual Match objects, iterate the collection by using a foreach (in C#) or For Each...Next (in Visual Basic) construct, or use the MatchCollection.Item[Int32] property to retrieve a specific Match object either by index or by name. 您也可以依索引 (從零到集合中的物件數減一) 從集合擷取個別 Match 物件。You can also retrieve individual Match objects from the collection by iterating the collection by index, from zero to one less that the number of objects in the collection. 不過,此方法不會利用延遲評估,因為它會存取 MatchCollection.Count 屬性。However, this method does not take advantage of lazy evaluation, because it accesses the MatchCollection.Count property.

    下列範例會使用 MatchMatchCollection...foreach 建構逐一查看集合,以從 For Each 物件擷取個別 Next 物件。The following example retrieves individual Match objects from a MatchCollection object by iterating the collection using the foreach or For Each...Next construct. 規則運算式會單純比對輸入字串中的字串 "abc"。The regular expression simply matches the string "abc" in the input string.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          foreach (Match match in Regex.Matches(input, pattern))
             Console.WriteLine("{0} found at position {1}.", 
                               match.Value, match.Index);
       }
    }
    // The example displays the following output:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "abc"
          Dim input As String = "abc123abc456abc789"
          For Each match As Match In Regex.Matches(input, pattern)
             Console.WriteLine("{0} found at position {1}.", _
                               match.Value, match.Index)
          Next                     
       End Sub
    End Module
    ' The example displays the following output:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    
  • 呼叫 Regex.Match 方法,它會傳回代表字串中第一個相符項目或字串一部分的 Match 物件。By calling the Regex.Match method, which returns a Match object that represents the first match in a string or a portion of a string. 您可以擷取 Match.Success 屬性的值,以判斷是否找到相符項目。You can determine whether the match has been found by retrieving the value of the Match.Success property. 若要擷取代表後續相符項目的 Match 物件,請重複呼叫 Match.NextMatch 方法,直到傳回之 Success 物件的 Match 屬性為 falseTo retrieve Match objects that represent subsequent matches, call the Match.NextMatch method repeatedly, until the Success property of the returned Match object is false.

    下列範例使用 Regex.Match(String, String)Match.NextMatch 方法來比對輸入字串中的字串 "abc"。The following example uses the Regex.Match(String, String) and Match.NextMatch methods to match the string "abc" in the input string.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          Match match = Regex.Match(input, pattern);
          while (match.Success)
          {
             Console.WriteLine("{0} found at position {1}.", 
                               match.Value, match.Index);
             match = match.NextMatch();                  
          }                     
       }
    }
    // The example displays the following output:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "abc"
          Dim input As String = "abc123abc456abc789"
          Dim match As Match = Regex.Match(input, pattern)
          Do While match.Success
             Console.WriteLine("{0} found at position {1}.", _
                               match.Value, match.Index)
             match = match.NextMatch()                  
          Loop                     
       End Sub
    End Module
    ' The example displays the following output:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    

Match 類別的兩個屬性會傳回集合物件:Two properties of the Match class return collection objects:

  • Match.Groups 屬性會傳回 GroupCollection 物件,其中包含符合規則運算式模式中之擷取群組的子字串相關資訊。The Match.Groups property returns a GroupCollection object that contains information about the substrings that match capturing groups in the regular expression pattern.

  • Match.Captures 屬性會傳回用法受限的 CaptureCollection 物件。The Match.Captures property returns a CaptureCollection object that is of limited use. 針對 Match 屬性為 Successfalse 物件,不會填入集合。The collection is not populated for a Match object whose Success property is false. 否則,就會包含具有與 Capture 物件相同資訊的單一 Match 物件。Otherwise, it contains a single Capture object that has the same information as the Match object.

如需這些物件的詳細資訊,請參閱本主題稍後的群組集合擷取集合兩節。For more information about these objects, see The Group Collection and The Capture Collection sections later in this topic.

Match 類別的兩個其他屬性會提供比對的相關資訊。Two additional properties of the Match class provide information about the match. Match.Value 屬性會傳回輸入字串中,符合規則運算式模式的子字串。The Match.Value property returns the substring in the input string that matches the regular expression pattern. Match.Index 屬性會傳回輸入字串中相符字串以零起始的開始位置。The Match.Index property returns the zero-based starting position of the matched string in the input string.

Match 類別也有兩個模式比對方法:The Match class also has two pattern-matching methods:

  • Match.NextMatch 方法會尋找目前 Match 物件代表之相符項目後面的相符項目,並傳回代表該相符項目的 Match 物件。The Match.NextMatch method finds the match after the match represented by the current Match object, and returns a Match object that represents that match.

  • Match.Result 方法會在相符字串上執行指定的取代作業,並傳回結果。The Match.Result method performs a specified replacement operation on the matched string and returns the result.

下列範例會使用 Match.Result 方法,在包含兩個小數位數的每個數字前面,加上 $ 符號和空格。The following example uses the Match.Result method to prepend a $ symbol and a space before every number that includes two fractional digits.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+(,\d{3})*\.\d{2}\b";
      string input = "16.32\n194.03\n1,903,672.08"; 

      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine(match.Result("$$ $&"));
   }
}
// The example displays the following output:
//       $ 16.32
//       $ 194.03
//       $ 1,903,672.08
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\d+(,\d{3})*\.\d{2}\b"
      Dim input As String = "16.32" + vbCrLf + "194.03" + vbCrLf + "1,903,672.08" 

      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine(match.Result("$$ $&"))
      Next
   End Sub
End Module
' The example displays the following output:
'       $ 16.32
'       $ 194.03
'       $ 1,903,672.08

規則運算式模式 \b\d+(,\d{3})*\.\d{2}\b 的定義如下表所示。The regular expression pattern \b\d+(,\d{3})*\.\d{2}\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\d+ 比對一個或多個十進位數字。Match one or more decimal digits.
(,\d{3})* 比對後面接三個十進位數字的零或多個逗號。Match zero or more occurrences of a comma followed by three decimal digits.
\. 比對小數點字元。Match the decimal point character.
\d{2} 比對兩個十進位數字。Match two decimal digits.
\b 結束字緣比對。End the match at a word boundary.

取代模式 $$ $& 指出相符的子字串應取代為貨幣符號 ($) ($$ 模式)、空格和相符項的值 ($& 模式)。The replacement pattern $$ $& indicates that the matched substring should be replaced by a dollar sign ($) symbol (the $$ pattern), a space, and the value of the match (the $& pattern).

回到頁首Back to top

群組集合The Group Collection

Match.Groups 屬性會傳回 GroupCollection 物件,其中包含單一比對中代表擷取群組的 Group 物件。The Match.Groups property returns a GroupCollection object that contains Group objects that represent captured groups in a single match. 集合中的第一個 Group 物件 (索引位置為 0) 代表整個比對。The first Group object in the collection (at index 0) represents the entire match. 後面接續的每個物件各代表單一擷取群組的結果。Each object that follows represents the results of a single capturing group.

您可以使用 Group 屬性,擷取集合中的個別 GroupCollection.Item[String] 物件。You can retrieve individual Group objects in the collection by using the GroupCollection.Item[String] property. 您可以依集合中的序數位置來擷取未具名群組,以及依名稱或依序數位置來擷取具名群組。You can retrieve unnamed groups by their ordinal position in the collection, and retrieve named groups either by name or by ordinal position. 未具名擷取會先出現在集合中,並依其出現在規則運算式模式中的順序,由左至右編排索引。Unnamed captures appear first in the collection, and are indexed from left to right in the order in which they appear in the regular expression pattern. 具名擷取的索引會依其出現在規則運算式模式中的順序,由左至右編排在未具名擷取之後。Named captures are indexed after unnamed captures, from left to right in the order in which they appear in the regular expression pattern. 若要判定特定規則運算式比對方法傳回的集合中,有哪些編號群組可用,您可以呼叫執行個體 Regex.GetGroupNumbers 方法。To determine what numbered groups are available in the collection returned for a particular regular expression matching method, you can call the instance Regex.GetGroupNumbers method. 若要判定集合中有哪些具名群組可用,您可以呼叫執行個體 Regex.GetGroupNames 方法。To determine what named groups are available in the collection, you can call the instance Regex.GetGroupNames method. 在用來分析任何規則運算式找到之相符項目的一般用途常式中,這兩種方法都特別好用。Both methods are particularly useful in general-purpose routines that analyze the matches found by any regular expression.

GroupCollection.Item[String] 屬性在 C# 是集合的索引子,在 Visual Basic 中是集合物件的預設屬性。The GroupCollection.Item[String] property is the indexer of the collection in C# and the collection object's default property in Visual Basic. 這表示,可以依索引 (若為具名群組,可依名稱) 來存取個別 Group 物件,如下所示:This means that individual Group objects can be accessed by index (or by name, in the case of named groups) as follows:

Group group = match.Groups[ctr];         
Dim group As Group = match.Groups(ctr)         

下列範例定義的規則運算式會使用群組建構來擷取日期的月、日和年。The following example defines a regular expression that uses grouping constructs to capture the month, day, and year of a date.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\w+)\s(\d{1,2}),\s(\d{4})\b";
      string input = "Born: July 28, 1989";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
         for (int ctr = 0; ctr <  match.Groups.Count; ctr++)
            Console.WriteLine("Group {0}: {1}", ctr, match.Groups[ctr].Value);
    }
}
// The example displays the following output:
//       Group 0: July 28, 1989
//       Group 1: July
//       Group 2: 28
//       Group 3: 1989
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(\w+)\s(\d{1,2}),\s(\d{4})\b"
      Dim input As String = "Born: July 28, 1989"
      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         For ctr As Integer = 0 To match.Groups.Count - 1
            Console.WriteLine("Group {0}: {1}", ctr, match.Groups(ctr).Value)
         Next      
      End If   
   End Sub
End Module
' The example displays the following output:
'       Group 0: July 28, 1989
'       Group 1: July
'       Group 2: 28
'       Group 3: 1989

規則運算式模式 \b(\w+)\s(\d{1,2}),\s(\d{4})\b 的定義如下表所示。The regular expression pattern \b(\w+)\s(\d{1,2}),\s(\d{4})\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
(\w+) 比對一個或多個文字字元。Match one or more word characters. 這是第一個擷取群組。This is the first capturing group.
\s 比對空白字元。Match a white-space character.
(\d{1,2}) 比對一個或兩個十進位數字。Match one or two decimal digits. 這是第二個擷取群組。This is the second capturing group.
, 比對逗號。Match a comma.
\s 比對空白字元。Match a white-space character.
(\d{4}) 比對四個十進位數字。Match four decimal digits. 這是第三個擷取群組。This is the third capturing group.
\b 結束字邊界比對。End the match on a word boundary.

回到頁首Back to top

擷取群組The Captured Group

Group 類別代表單一擷取群組的結果。The Group class represents the result from a single capturing group. Item[String] 屬性傳回之 GroupCollection 物件的 Match.Groups 屬性,會傳回代表規則運算式中定義之擷取群組的群組物件。Group objects that represent the capturing groups defined in a regular expression are returned by the Item[String] property of the GroupCollection object returned by the Match.Groups property. Item[String] 屬性是 Group 類別的索引子 (在 C# 中) 及預設屬性 (在 Visual Basic 中)。The Item[String] property is the indexer (in C#) and the default property (in Visual Basic) of the Group class. 您也可以使用 foreachFor Each 建構,逐一查看集合來擷取個別成員。You can also retrieve individual members by iterating the collection using the foreach or For Each construct. 如需範例,請參閱上一節。For an example, see the previous section.

下列範例會使用巢狀群組建構,將子字串擷取至群組中。The following example uses nested grouping constructs to capture substrings into groups. 規則運算式模式 (a(b))c 會相符字串 "abc"。The regular expression pattern (a(b))c matches the string "abc". 它會將子字串 "ab" 指派給第一個擷取群組,並將子字串 "b" 指派給第二個擷取群組。It assigns the substring "ab" to the first capturing group, and the substring "b" to the second capturing group.

   List<int> matchposition = new List<int>();
   List<string> results = new List<string>();
   // Define substrings abc, ab, b.
   Regex r = new Regex("(a(b))c"); 
   Match m = r.Match("abdabc");
   for (int i = 0; m.Groups[i].Value != ""; i++) 
   {
      // Add groups to string array.
      results.Add(m.Groups[i].Value); 
      // Record character position.
      matchposition.Add(m.Groups[i].Index); 
   }

   // Display the capture groups.
   for (int ctr = 0; ctr < results.Count; ctr++)
      Console.WriteLine("{0} at position {1}", 
                        results[ctr], matchposition[ctr]);
   // The example displays the following output:
   //       abc at position 3
   //       ab at position 3
   //       b at position 4
 Dim matchposition As New List(Of Integer)
 Dim results As New List(Of String)
 ' Define substrings abc, ab, b.
 Dim r As New Regex("(a(b))c") 
 Dim m As Match = r.Match("abdabc")
 Dim i As Integer = 0
 While Not (m.Groups(i).Value = "")    
    ' Add groups to string array.
    results.Add(m.Groups(i).Value)     
    ' Record character position. 
    matchposition.Add(m.Groups(i).Index) 
     i += 1
 End While
 
 ' Display the capture groups.
 For ctr As Integer = 0 to results.Count - 1
    Console.WriteLine("{0} at position {1}", _ 
                      results(ctr), matchposition(ctr))
 Next                     
' The example displays the following output:
'       abc at position 3
'       ab at position 3
'       b at position 4

下列範例會使用具名群組建構,從包含 "DATANAME:VALUE" 格式 (規則運算式會在冒號 (:) 處分割) 資料的字串擷取子字串。The following example uses named grouping constructs to capture substrings from a string that contains data in the format "DATANAME:VALUE", which the regular expression splits at the colon (:).

Regex r = new Regex("^(?<name>\\w+):(?<value>\\w+)");
Match m = r.Match("Section1:119900");
Console.WriteLine(m.Groups["name"].Value);
Console.WriteLine(m.Groups["value"].Value);
// The example displays the following output:
//       Section1
//       119900
Dim r As New Regex("^(?<name>\w+):(?<value>\w+)")
Dim m As Match = r.Match("Section1:119900")
Console.WriteLine(m.Groups("name").Value)
Console.WriteLine(m.Groups("value").Value)
' The example displays the following output:
'       Section1
'       119900

規則運算式模式 ^(?<name>\w+):(?<value>\w+) 的定義如下表所示。The regular expression pattern ^(?<name>\w+):(?<value>\w+) is defined as shown in the following table.

模式Pattern 說明Description
^ 在輸入字串的開頭開始比對。Begin the match at the beginning of the input string.
(?<name>\w+) 比對一個或多個文字字元。Match one or more word characters. 此擷取群組的名稱為 nameThe name of this capturing group is name.
: 比對冒號。Match a colon.
(?<value>\w+) 比對一個或多個文字字元。Match one or more word characters. 此擷取群組的名稱為 valueThe name of this capturing group is value.

Group 類別之屬性會提供已擷取群組的相關資訊:Group.Value 屬性包含擷取的子字串、Group.Index 屬性會指出已擷取群組在輸入文字中的開始位置、Group.Length 屬性包含已擷取文字的長度,而 Group.Success 屬性會指出子字串是否符合擷取群組所定義的模式。The properties of the Group class provide information about the captured group: The Group.Value property contains the captured substring, the Group.Index property indicates the starting position of the captured group in the input text, the Group.Length property contains the length of the captured text, and the Group.Success property indicates whether a substring matched the pattern defined by the capturing group.

將數量詞套用至群組 (如需詳細資訊,請參閱數量詞) 會以兩種方式來修改每個擷取群組各一個擷取的關聯性:Applying quantifiers to a group (for more information, see Quantifiers) modifies the relationship of one capture per capturing group in two ways:

  • 如果將 **? 數量詞 (可指定零或多個相符項目) 套用至群組,擷取群組在輸入字串中可會沒有相符項目。If the * or *? quantifier (which specifies zero or more matches) is applied to a group, a capturing group may not have a match in the input string. 沒有擷取文字時,Group 物件的屬性會設定如下表所示。When there is no captured text, the properties of the Group object are set as shown in the following table.

    群組屬性Group property Value
    Success false
    Value String.Empty
    Length 00

    下列範例提供一個實例。The following example provides an illustration. 在規則運算式模式 aaa(bbb)*ccc 中,第一個擷取群組 (子字串 "bbb") 可比對零或多次。In the regular expression pattern aaa(bbb)*ccc, the first capturing group (the substring "bbb") can be matched zero or more times. 因為輸入字串 "aaaccc" 符合模式,所以擷取群組沒有相符項目。Because the input string "aaaccc" matches the pattern, the capturing group does not have a match.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "aaa(bbb)*ccc";
          string input = "aaaccc";
          Match match = Regex.Match(input, pattern);
          Console.WriteLine("Match value: {0}", match.Value);
          if (match.Groups[1].Success)
             Console.WriteLine("Group 1 value: {0}", match.Groups[1].Value);
          else
             Console.WriteLine("The first capturing group has no match.");
       }
    }
    // The example displays the following output:
    //       Match value: aaaccc
    //       The first capturing group has no match.
    
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "aaa(bbb)*ccc"
          Dim input As String = "aaaccc"
          Dim match As Match = Regex.Match(input, pattern)
          Console.WriteLine("Match value: {0}", match.Value)
          If match.Groups(1).Success Then
             Console.WriteLine("Group 1 value: {0}", match.Groups(1).Value)
          Else
             Console.WriteLine("The first capturing group has no match.")
         End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       Match value: aaaccc
    '       The first capturing group has no match.
    
  • 數量詞可以比對多次出現的擷取群組定義的模式。Quantifiers can match multiple occurrences of a pattern that is defined by a capturing group. 在此情況下,Value 物件的 LengthGroup 屬性只包含最後擷取之子字串的相關資訊。In this case, the Value and Length properties of a Group object contain information only about the last captured substring. 例如,下列規則運算式會比對以句點結尾的單一句子。For example, the following regular expression matches a single sentence that ends in a period. 其使用兩個群組建構:第一個群組建構會擷取個別文字和空格字元;第二個群組建構會擷取個別文字。It uses two grouping constructs: The first captures individual words along with a white-space character; the second captures individual words. 如範例輸出所示,雖然規則運算式成功擷取了整個句子,但是第二個擷取群組只擷取了最後一個字。As the output from the example shows, although the regular expression succeeds in capturing an entire sentence, the second capturing group captures only the last word.

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = @"\b((\w+)\s?)+\.";
          string input = "This is a sentence. This is another sentence.";
          Match match = Regex.Match(input, pattern);
          if (match.Success)
          {
             Console.WriteLine("Match: " + match.Value);
             Console.WriteLine("Group 2: " + match.Groups[2].Value);
          }   
       }
    }
    // The example displays the following output:
    //       Match: This is a sentence.
    //       Group 2: sentence
    
    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "\b((\w+)\s?)+\."
          Dim input As String = "This is a sentence. This is another sentence."
          Dim match As Match = Regex.Match(input, pattern)
          If match.Success Then
             Console.WriteLine("Match: " + match.Value)
             Console.WriteLine("Group 2: " + match.Groups(2).Value)
          End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       Match: This is a sentence.
    '       Group 2: sentence
    

回到頁首Back to top

擷取集合The Capture Collection

Group 物件只包含最後一個擷取的相關資訊。The Group object contains information only about the last capture. 不過,您仍可從 CaptureCollection 屬性傳回的 Group.Captures 物件,取得擷取群組所建立的一整組擷取。However, the entire set of captures made by a capturing group is still available from the CaptureCollection object that is returned by the Group.Captures property. 集合的每個成員都是 Capture 物件,代表擷取群組所建立的擷取,並依照擷取的順序排列 (因此,順序為在輸入字串中比對擷取群組的順序,由左至右排列)。Each member of the collection is a Capture object that represents a capture made by that capturing group, in the order in which they were captured (and, therefore, in the order in which the captured strings were matched from left to right in the input string). 您可以從集合擷取個別 Capture 物件,有兩種方式:You can retrieve individual Capture objects from the collection in either of two ways:

  • 使用 foreach (在 C# 中) 或 For Each (在 Visual Basic 中) 之類的建構逐一查看集合。By iterating through the collection using a construct such as foreach (in C#) or For Each (in Visual Basic).

  • 使用 CaptureCollection.Item[Int32] 屬性,依索引擷取特定物件。By using the CaptureCollection.Item[Int32] property to retrieve a specific object by index. Item[Int32] 屬性是 CaptureCollection 物件的預設屬性 (在 Visual Basic 中) 或索引子 (在 C# 中)。The Item[Int32] property is the CaptureCollection object's default property (in Visual Basic) or indexer (in C#).

如果沒有將數量詞套用至擷取群組,則 CaptureCollection 物件會包含單一較無用處的 Capture 物件,因為其提供與其 Group 物件相同之相符項目的相關資訊。If a quantifier is not applied to a capturing group, the CaptureCollection object contains a single Capture object that is of little interest, because it provides information about the same match as its Group object. 如果將數量詞套用至擷取群組,則 CaptureCollection 物件包含擷取群組建立的所有擷取,而集合的最後一個成員代表與 Group 物件相同的擷取。If a quantifier is applied to a capturing group, the CaptureCollection object contains all captures made by the capturing group, and the last member of the collection represents the same capture as the Group object.

例如,如果您使用規則運算式模式 ((a(b))c)+ (其中 + 數量詞指定一或多個比對),以從字串 "abcabcabc" 擷取相符項目,則每個 CaptureCollection 物件的 Group 物件各包含三個成員。For example, if you use the regular expression pattern ((a(b))c)+ (where the + quantifier specifies one or more matches) to capture matches from the string "abcabcabc", the CaptureCollection object for each Group object contains three members.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "((a(b))c)+";
      string input = "abcabcabc";
      
      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Match: '{0}' at position {1}",  
                           match.Value, match.Index);
         GroupCollection groups = match.Groups;
         for (int ctr = 0; ctr < groups.Count; ctr++) {
            Console.WriteLine("   Group {0}: '{1}' at position {2}", 
                              ctr, groups[ctr].Value, groups[ctr].Index);
            CaptureCollection captures = groups[ctr].Captures;
            for (int ctr2 = 0; ctr2 < captures.Count; ctr2++) {
               Console.WriteLine("      Capture {0}: '{1}' at position {2}", 
                                 ctr2, captures[ctr2].Value, captures[ctr2].Index);
            }                     
         }
      }
   }
}
// The example displays the following output:
//       Match: 'abcabcabc' at position 0
//          Group 0: 'abcabcabc' at position 0
//             Capture 0: 'abcabcabc' at position 0
//          Group 1: 'abc' at position 6
//             Capture 0: 'abc' at position 0
//             Capture 1: 'abc' at position 3
//             Capture 2: 'abc' at position 6
//          Group 2: 'ab' at position 6
//             Capture 0: 'ab' at position 0
//             Capture 1: 'ab' at position 3
//             Capture 2: 'ab' at position 6
//          Group 3: 'b' at position 7
//             Capture 0: 'b' at position 1
//             Capture 1: 'b' at position 4
//             Capture 2: 'b' at position 7
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "((a(b))c)+"
      Dim input As STring = "abcabcabc"
      
      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         Console.WriteLine("Match: '{0}' at position {1}", _ 
                           match.Value, match.Index)
         Dim groups As GroupCollection = match.Groups
         For ctr As Integer = 0 To groups.Count - 1
            Console.WriteLine("   Group {0}: '{1}' at position {2}", _
                              ctr, groups(ctr).Value, groups(ctr).Index)
            Dim captures As CaptureCollection = groups(ctr).Captures
            For ctr2 As Integer = 0 To captures.Count - 1
               Console.WriteLine("      Capture {0}: '{1}' at position {2}", _
                                 ctr2, captures(ctr2).Value, captures(ctr2).Index)
            Next
         Next
      End If
   End Sub
End Module
' The example dosplays the following output:
'       Match: 'abcabcabc' at position 0
'          Group 0: 'abcabcabc' at position 0
'             Capture 0: 'abcabcabc' at position 0
'          Group 1: 'abc' at position 6
'             Capture 0: 'abc' at position 0
'             Capture 1: 'abc' at position 3
'             Capture 2: 'abc' at position 6
'          Group 2: 'ab' at position 6
'             Capture 0: 'ab' at position 0
'             Capture 1: 'ab' at position 3
'             Capture 2: 'ab' at position 6
'          Group 3: 'b' at position 7
'             Capture 0: 'b' at position 1
'             Capture 1: 'b' at position 4
'             Capture 2: 'b' at position 7

下列範例使用規則運算式 (Abc)+,在字串 "XYZAbcAbcAbcXYZAbcAb" 中尋找一或多次連續執行的字串 "Abc"。The following example uses the regular expression (Abc)+ to find one or more consecutive runs of the string "Abc" in the string "XYZAbcAbcAbcXYZAbcAb". 此範例說明如何使用 Group.Captures 屬性來傳回多個擷取子字串群組。The example illustrates the use of the Group.Captures property to return multiple groups of captured substrings.

   int counter;
   Match m;
   CaptureCollection cc;
   GroupCollection gc;

   // Look for groupings of "Abc".
   Regex r = new Regex("(Abc)+"); 
   // Define the string to search.
   m = r.Match("XYZAbcAbcAbcXYZAbcAb"); 
   gc = m.Groups;

   // Display the number of groups.
   Console.WriteLine("Captured groups = " + gc.Count.ToString());

   // Loop through each group.
   for (int i=0; i < gc.Count; i++) 
   {
      cc = gc[i].Captures;
      counter = cc.Count;
       
      // Display the number of captures in this group.
      Console.WriteLine("Captures count = " + counter.ToString());
       
      // Loop through each capture in the group.
      for (int ii = 0; ii < counter; ii++) 
      {
         // Display the capture and its position.
         Console.WriteLine(cc[ii] + "   Starts at character " + 
              cc[ii].Index);
      }
   }
}
// The example displays the following output:
//       Captured groups = 2
//       Captures count = 1
//       AbcAbcAbc   Starts at character 3
//       Captures count = 3
//       Abc   Starts at character 3
//       Abc   Starts at character 6
//       Abc   Starts at character 9  
Dim counter As Integer
Dim m As Match
Dim cc As CaptureCollection
Dim gc As GroupCollection

' Look for groupings of "Abc".
Dim r As New Regex("(Abc)+") 
' Define the string to search.
m = r.Match("XYZAbcAbcAbcXYZAbcAb")
gc = m.Groups

' Display the number of groups.
Console.WriteLine("Captured groups = " & gc.Count.ToString())

' Loop through each group.
Dim i, ii As Integer
For i = 0 To gc.Count - 1
    cc = gc(i).Captures
    counter = cc.Count
    
    ' Display the number of captures in this group.
    Console.WriteLine("Captures count = " & counter.ToString())
    
    ' Loop through each capture in the group.            
    For ii = 0 To counter - 1
        ' Display the capture and its position.
        Console.WriteLine(cc(ii).ToString() _
            & "   Starts at character " & cc(ii).Index.ToString())
    Next ii
Next i
' The example displays the following output:
'       Captured groups = 2
'       Captures count = 1
'       AbcAbcAbc   Starts at character 3
'       Captures count = 3
'       Abc   Starts at character 3
'       Abc   Starts at character 6
'       Abc   Starts at character 9  

回到頁首Back to top

個別擷取The Individual Capture

Capture 類別包含單一子運算式擷取的結果。The Capture class contains the results from a single subexpression capture. Capture.Value 屬性包含相符的文字,而 Capture.Index 屬性指出輸入字串中以零起始的位置,也就是相符的子字串開始的位置。The Capture.Value property contains the matched text, and the Capture.Index property indicates the zero-based position in the input string at which the matched substring begins.

下列範例會針對所選城市的氣溫剖析輸入字串。The following example parses an input string for the temperature of selected cities. 逗號 (",") 用來分隔城市及其氣溫,而分號 (";") 用來分隔每個城市的資料。A comma (",") is used to separate a city and its temperature, and a semicolon (";") is used to separate each city's data. 整個輸入字串代表單一比對。The entire input string represents a single match. 在規則運算式模式 ((\w+(\s\w+)*),(\d+);)+ (用來剖析字串) 中,城市名稱指派給第二個擷取群組,而氣溫指派給第四個擷取群組。In the regular expression pattern ((\w+(\s\w+)*),(\d+);)+, which is used to parse the string, the city name is assigned to the second capturing group, and the temperature is assigned to the fourth capturing group.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;"; 
      string pattern = @"((\w+(\s\w+)*),(\d+);)+";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Current temperatures:");
         for (int ctr = 0; ctr < match.Groups[2].Captures.Count; ctr++)
            Console.WriteLine("{0,-20} {1,3}", match.Groups[2].Captures[ctr].Value, 
                              match.Groups[4].Captures[ctr].Value);
      }
   }
}
// The example displays the following output:
//       Current temperatures:
//       Miami                 78
//       Chicago               62
//       New York              67
//       San Francisco         59
//       Seattle               58
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;" 
      Dim pattern As String = "((\w+(\s\w+)*),(\d+);)+"
      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         Console.WriteLine("Current temperatures:")
         For ctr As Integer = 0 To match.Groups(2).Captures.Count - 1
            Console.WriteLine("{0,-20} {1,3}", match.Groups(2).Captures(ctr).Value, _
                              match.Groups(4).Captures(ctr).Value)
         Next
      End If
   End Sub
End Module
' The example displays the following output:
'       Current temperatures:
'       Miami                 78
'       Chicago               62
'       New York              67
'       San Francisco         59
'       Seattle               58

規則運算式的定義如下表所示。The regular expression is defined as shown in the following table.

模式Pattern 說明Description
\w+ 比對一個或多個文字字元。Match one or more word characters.
(\s\w+)* 比對出現零或多次、後接一或多個文字字元的空格字元。Match zero or more occurrences of a white-space character followed by one or more word characters. 此模式會比對多字的城市名稱。This pattern matches multi-word city names. 這是第三個擷取群組。This is the third capturing group.
(\w+(\s\w+)*) 比對一或多個文字字元,其後面接出現零或多次的空格字元,以及一或多個文字字元。Match one or more word characters followed by zero or more occurrences of a white-space character and one or more word characters. 這是第二個擷取群組。This is the second capturing group.
, 比對逗號。Match a comma.
(\d+) 比對一或多個數字。Match one or more digits. 這是第四個擷取群組。This is the fourth capturing group.
; 比對分號。Match a semicolon.
((\w+(\s\w+)*),(\d+);)+ 一或多次比對文字的模式,該文字後面接任何其他文字,後面再接逗號、一或多個數字和分號。Match the pattern of a word followed by any additional words followed by a comma, one or more digits, and a semicolon, one or more times. 這是第一個擷取群組。This is the first capturing group.

另請參閱See also