Поделиться через


Match Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents the results from a single regular expression match.

Inheritance Hierarchy

System.Object
  System.Text.RegularExpressions.Capture
    System.Text.RegularExpressions.Group
      System.Text.RegularExpressions.Match

Namespace:  System.Text.RegularExpressions
Assembly:  System (in System.dll)

Syntax

'Declaration
Public Class Match _
    Inherits Group
public class Match : Group

The Match type exposes the following members.

Properties

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Captures 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 RegexOptions.RightToLeft option). The collection may have zero or more items. (Inherited from Group.)
Public propertyStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 Empty Gets the empty group. All failed matches return this empty match.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Groups Gets a collection of groups matched by the regular expression.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Index The position in the original string where the first character of the captured substring was found. (Inherited from Capture.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Length The length of the captured substring. (Inherited from Capture.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Success Gets a value indicating whether the match is successful. (Inherited from Group.)
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Value Gets the captured substring from the input string. (Inherited from Capture.)

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 NextMatch 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 beyond the last matched character).
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Result Returns the expansion of the specified replacement pattern.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Gets the captured substring from the input string. (Inherited from Capture.)

Top

Remarks

The Match object is immutable and has no public constructor. An instance of the Match class is returned by the Regex.Match method and represents the first pattern match in a string. Subsequent matches are represented by Match objects returned by the Match.NextMatch method. In addition, a MatchCollection object that consists of zero, one, or more Match objects is returned by the Regex.Matches method.

If the Regex.Matches method fails to match a regular expression pattern in an input string, it returns an empty MatchCollection object. You can then use a foreach construct in C# or a For Each construct in Visual Basic to iterate the collection.

If the Regex.Match method fails to match the regular expression pattern, it returns a Match object that is equal to Match.Empty. 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.
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.
   outputBlock.Text += String.Format("'{0}' was found at position {1} in '{2}'.", _
                     match.Value, match.Index + 1, input) & vbCrLf
Else
   outputBlock.Text += String.Format("The pattern '{0}' was not found in '{1}'.", _
                     pattern, input) & vbCrLf
End If
// 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.
   outputBlock.Text += String.Format("'{0}' was found at position {1} in '{2}'.",
                     match.Value, match.Index + 1, input) + "\n";
else
   outputBlock.Text += String.Format("The pattern '{0}' was not found in '{1}'.",
                     pattern, input) + "\n";

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.

Because a single match can involve multiple capturing groups, Match has a Groups property that returns the GroupCollection. The GroupCollection has accessors that return each group. The 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.

Examples

The following examples use the regular expression Console\.Write(Line)?. The regular expression is interpreted as follows:

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)?

Match zero or one occurrence of the string "Line".

Example 1

The following example calls the Regex.Matches(String, String) method to retrieve all pattern matches in an input string. It then iterates the Match objects in the returned MatchCollection object to display information about each match.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
Try
      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
         outputBlock.Text += String.Format("'{0}' found in the source code at position {1}.", _
                           match.Value, match.Index) & vbCrLf
      Next
Catch e as Exception
   outputBlock.Text += e.GetType().Name + ": " + e.Message
end Try
   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.
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      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)
         outputBlock.Text += String.Format("'{0}' found in the source code at position {1}.",
                           match.Value, match.Index) + "\n";
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 112.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 206.

Example 2

The following example calls the Match(String, String) and NextMatch methods to retrieve one match at a time.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      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
         outputBlock.Text += String.Format("'{0}' found in the source code at position {1}.", _
                           match.Value, match.Index) & vbCrLf
         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.
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      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)
      {
         outputBlock.Text += String.Format("'{0}' found in the source code at position {1}.",
                           match.Value, match.Index) + "\n";
         match = match.NextMatch();
      }
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 112.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 207.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.