Match Match Match Match Class

定義

表示單一規則運算式 (Regular Expression) 比對的結果。Represents the results from a single regular expression match.

public ref class Match : System::Text::RegularExpressions::Group
[System.Serializable]
public class Match : System.Text.RegularExpressions.Group
type Match = class
    inherit Group
Public Class Match
Inherits Group
繼承
屬性

範例

下列範例會使用正則運算式Console\.Write(Line)?The following examples use the regular expression Console\.Write(Line)?. 規則運算式解譯如下:The regular expression is interpreted as follows:

主控台\。寫入Console\.Write 比對字串 "Console.Write"。Match the string "Console.Write". 請注意, "." 字元會經過轉義, 使其被視為常值期間, 而不是符合任何字元的萬用字元。Note that the "." character is escaped so that it is interpreted as a literal period rather than as a wildcard that matches any character.
(行)?(Line)? 比對出現零或一次的字串 "Line"。Match zero or one occurrence of the string "Line".

範例1Example 1

下列範例會呼叫Regex.Matches(String, String)方法, 以取出輸入字串中的所有模式相符專案。The following example calls the Regex.Matches(String, String) method to retrieve all pattern matches in an input string. 然後, 它會Match逐一查看所傳回MatchCollection物件中的物件, 以顯示每個相符項的相關資訊。It then iterates the Match objects in the returned MatchCollection object to display information about each match.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   
      
      string pattern = @"Console\.Write(Line)?";
      MatchCollection matches = Regex.Matches(input, pattern);
      foreach (Match match in matches)
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 115.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 211.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
                            "For ctr As Integer = values.GetLowerBound(1) To values.GetUpperBound(1)" & vbCrLf & _
                            "   Console.Write(values(ctr))" & vbCrLf & _
                            "   If ctr < values.GetUpperBound(1) Then Console.Write("", "")" & vbCrLf & _
                            "Next" & vbCrLf & _
                            "Console.WriteLine()"   
      Dim pattern As String = "Console\.Write(Line)?"
      Dim matches As MatchCollection = Regex.Matches(input, pattern)
      For Each match As Match In matches
         Console.WriteLine("'{0}' found in the source code at position {1}.", _ 
                           match.Value, match.Index)       
      Next                            
   End Sub
End Module
' The example displays the following output:
'    'Console.Write' found in the source code at position 115.
'    'Console.Write' found in the source code at position 184.
'    'Console.WriteLine' found in the source code at position 211.

範例2Example 2

下列範例會呼叫Match(String, String)NextMatch方法, 以一次取得一個相符項。The following example calls the Match(String, String) and NextMatch methods to retrieve one match at a time.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   
      string pattern = @"Console\.Write(Line)?";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
         match = match.NextMatch();
      }
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 115.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 211.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Dim values() As Integer = { 1, 2, 3 }" & vbCrLf & _
                            "For ctr As Integer = values.GetLowerBound(1) To values.GetUpperBound(1)" & vbCrLf & _
                            "   Console.Write(values(ctr))" & vbCrLf & _
                            "   If ctr < values.GetUpperBound(1) Then Console.Write("", "")" & vbCrLf & _
                            "Next" & vbCrLf & _
                            "Console.WriteLine()"   
      Dim pattern As String = "Console\.Write(Line)?"
      Dim match As Match = Regex.Match(input, pattern)
      Do While match.Success
         Console.WriteLine("'{0}' found in the source code at position {1}.", _ 
                           match.Value, match.Index)
         match = match.NextMatch()                  
      Loop                            
   End Sub
End Module
' The example displays the following output:
'    'Console.Write' found in the source code at position 115.
'    'Console.Write' found in the source code at position 184.
'    'Console.WriteLine' found in the source code at position 211.

備註

物件Match是不可變的, 而且沒有公用的函式。The Match object is immutable and has no public constructor. Regex.Match方法會傳回Match類別的實例, 並以字串表示第一個模式比對。An instance of the Match class is returned by the Regex.Match method and represents the first pattern match in a string. 後續的比對Match Match.NextMatch是由方法所傳回的物件表示。Subsequent matches are represented by Match objects returned by the Match.NextMatch method. 此外, MatchCollection Regex.Matches方法會傳回包含零個、一個或多個Match物件的物件。In addition, a MatchCollection object that consists of zero, one, or more Match objects is returned by the Regex.Matches method.

如果方法無法符合輸入字串中的正則運算式模式, 則會傳回空MatchCollection的物件。 Regex.MatchesIf the Regex.Matches method fails to match a regular expression pattern in an input string, it returns an empty MatchCollection object. 接著, 您可以使用foreach中C#的結構, For Each或 Visual Basic 中的結構來反復查看集合。You can then use a foreach construct in C# or a For Each construct in Visual Basic to iterate the collection.

如果方法無法符合正則運算式模式, 則Match會傳回等於的Match.Empty物件。 Regex.MatchIf the Regex.Match method fails to match the regular expression pattern, it returns a Match object that is equal to Match.Empty. 您可以使用Success屬性來判斷相符是否成功。You can use the Success property to determine whether the match was successful. 下列範例提供一個實例。The following example provides an illustration.

// Search for a pattern that is not found in the input string.
string pattern = "dog";
string input = "The cat saw the other cats playing in the back yard.";
Match match = Regex.Match(input, pattern);
if (match.Success )
   // Report position as a one-based integer.
   Console.WriteLine("'{0}' was found at position {1} in '{2}'.", 
                     match.Value, match.Index + 1, input);
else
   Console.WriteLine("The pattern '{0}' was not found in '{1}'.",
                     pattern, input);
' Search for a pattern that is not found in the input string.
Dim pattern As String = "dog"
Dim input As String = "The cat saw the other cats playing in the back yard."
Dim match As Match = Regex.Match(input, pattern)
If match.Success Then
   ' Report position as a one-based integer.
   Console.WriteLine("'{0}' was found at position {1} in '{2}'.", _ 
                     match.Value, match.Index + 1, input)
Else
   Console.WriteLine("The pattern '{0}' was not found in '{1}'.", _
                     pattern, input)
End If

如果模式比對成功, Value屬性會包含相符的子字串Index , 屬性會指出Length輸入字串中相符子字串之以零為起始的開始位置, 而屬性則表示輸入字串中相符的子字串長度。If a pattern match is successful, the Value property contains the matched substring, the Index property indicates the zero-based starting position of the matched substring in the input string, and the Length property indicates the length of matched substring in the input string.

因為單一相符項可能牽涉到多個捕捉Match群組, Groups所以具有會傳回GroupCollection的屬性。Because a single match can involve multiple capturing groups, Match has a Groups property that returns the GroupCollection. 實例本身相當於集合中的第一個物件 (Match.Groups(0)位於Match.Groups[0] Visual Basic), 代表整個相符的。 MatchThe Match instance itself is equivalent to the first object in the collection, at Match.Groups[0] (Match.Groups(0) in Visual Basic), which represents the entire match. 您可以透過下列方式存取相符的中的已捕獲群組:You can access the captured groups in a match in the following ways:

  • 您可以GroupCollection C#使用 () 或For Each (Visual Basic) 結構來逐一查看物件的成員。 foreachYou can iterate the members of the GroupCollection object by using a foreach (C#) or For Each (Visual Basic) construct.

  • 您可以使用GroupCollection.Item[Int32]屬性, 依捕捉群組的數目抓取群組。You can use the GroupCollection.Item[Int32] property to retrieve groups by the number of the capturing group. 請注意, 您可以藉由呼叫實例Regex.GetGroupNumbers方法, 判斷正則運算式中有哪些編號群組。Note that you can determine which numbered groups are present in a regular expression by calling the instance Regex.GetGroupNumbers method.

  • 您可以使用GroupCollection.Item[String]屬性, 依「捕捉群組」的名稱來抓取「群組」。You can use the GroupCollection.Item[String] property to retrieve groups by the name of the capturing group. 請注意, 您可以藉由呼叫實例Regex.GetGroupNames()方法, 判斷正則運算式中有哪些命名群組。Note that you can determine which named groups are present in a regular expression by calling the instance Regex.GetGroupNames() method.

屬性

Captures Captures Captures Captures

依照最內層最左邊為優先的順序,取得符合擷取群組的所有擷取的集合 (如果規則運算式使用 RightToLeft 選項修改,則依照最內層最右邊為優先的順序),Gets a collection of all the captures matched by the capturing group, in innermost-leftmost-first order (or innermost-rightmost-first order if the regular expression is modified with the RightToLeft option). 集合可能有零個或更多項目。The collection may have zero or more items.

(Inherited from Group)
Empty Empty Empty Empty

取得空白群組,Gets the empty group. 所有失敗的比對會傳回這個空白比對。All failed matches return this empty match.

Groups Groups Groups Groups

取得符合規則運算式的群組集合。Gets a collection of groups matched by the regular expression.

Index Index Index Index

在原始字串中找到擷取的子字串的第一個字元之位置。The position in the original string where the first character of the captured substring is found.

(Inherited from Capture)
Length Length Length Length

取得所擷取子字串的長度。Gets the length of the captured substring.

(Inherited from Capture)
Name Name Name Name

傳回目前執行個體所代表的擷取群組名稱。Returns the name of the capturing group represented by the current instance.

(Inherited from Group)
Success Success Success Success

取得值,指出比對是否成功。Gets a value indicating whether the match is successful.

(Inherited from Group)
Value Value Value Value

從輸入字串取得擷取的子字串。Gets the captured substring from the input string.

(Inherited from Capture)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
NextMatch() NextMatch() NextMatch() NextMatch()

自最後一個比對結束的位置 (在最後符合字元之後的字元) 開始,傳回具有下一個比對結果的新 Match 物件。Returns a new Match object with the results for the next match, starting at the position at which the last match ended (at the character after the last matched character).

Result(String) Result(String) Result(String) Result(String)

傳回所指定取代模式的展開 (Expansion)。Returns the expansion of the specified replacement pattern.

Synchronized(Match) Synchronized(Match) Synchronized(Match) Synchronized(Match)

傳回 Match 執行個體,就相當於可在多個執行緒之間提供了一個可共用的執行個體。Returns a Match instance equivalent to the one supplied that is suitable to share between multiple threads.

ToString() ToString() ToString() ToString()

擷取已透過呼叫 Value 屬性從輸入字串擷取的子字串。Retrieves the captured substring from the input string by calling the Value property.

(Inherited from Capture)

適用於

另請參閱