MatchCollection MatchCollection MatchCollection MatchCollection Class

Definition

Represents the set of successful matches found by iteratively applying a regular expression pattern to the input string.

public ref class MatchCollection : System::Collections::ICollection
[Serializable]
public class MatchCollection : System.Collections.ICollection
type MatchCollection = class
    interface ICollection
    interface IEnumerable
Public Class MatchCollection
Implements ICollection
Inheritance
MatchCollectionMatchCollectionMatchCollectionMatchCollection
Attributes
SerializableAttribute
Implements

Examples

The following example illustrates the use of the MatchCollection class to interrogate a set of Match instances.

#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumps over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
        
        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }
        
    }
	
}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumps over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54
Imports System
Imports System.Text.RegularExpressions

Public Module Test

    Public Sub Main()
        ' Define a regular expression for repeated words.
        Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", _
               RegexOptions.Compiled Or RegexOptions.IgnoreCase)

        ' Define a test string.        
        Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
        
        ' Find matches.
        Dim matches As MatchCollection = rx.Matches(text)

        ' Report the number of matches found.
        Console.WriteLine("{0} matches found in:", matches.Count)
        Console.WriteLine("   {0}", text)

        ' Report on each match.
        For Each match As Match In matches
            Dim groups As GroupCollection = match.Groups
            Console.WriteLine("'{0}' repeated at positions {1} and {2}", _ 
                              groups.Item("word").Value, _
                              groups.Item(0).Index, _
                              groups.Item(1).Index)
        Next
    End Sub
End Module
' The example produces the following output to the console:
'       3 matches found in:
'          The the quick brown fox  fox jumps over the lazy dog dog.
'       'The' repeated at positions 0 and 4
'       'fox' repeated at positions 20 and 25
'       'dog' repeated at positions 50 and 54

Remarks

The collection is immutable (read-only) and has no public constructor. The Regex.Matches method returns a MatchCollection object.

The collection contains zero or more System.Text.RegularExpressions.Match objects. If the match is successful, the collection is populated with one System.Text.RegularExpressions.Match object for each match found in the input string. If the match is unsuccessful, the collection contains no System.Text.RegularExpressions.Match objects, and its Count property equals zero.

When applying a regular expression pattern to a particular input string, the regular expression engine uses either of two techniques to build the MatchCollection object:

  • Direct evaluation.

    The MatchCollection object is populated all at once, with all matches resulting from a particular call to the Regex.Matches method. This technique is used when the collection's Count property is accessed. It typically is the more expensive method of populating the collection and entails a greater performance hit.

  • Lazy evaluation.

    The MatchCollection object is populated as needed on a match-by-match basis. It is equivalent to the regular expression engine calling the Regex.Match method repeatedly and adding each match to the collection. This technique is used when the collection is accessed through its GetEnumerator method, or when it is accessed using the foreach statement (in C#) or the For Each...Next statement (in Visual Basic).

To iterate through the members of the collection, you should use the collection iteration construct provided by your language (such as foreach in C# and For EachNext in Visual Basic) instead of retrieving the enumerator that is returned by the GetEnumerator method.

Properties

Count Count Count Count

Gets the number of matches.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

Gets a value that indicates whether the collection is read only.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

Gets a value indicating whether access to the collection is synchronized (thread-safe).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

Gets an individual member of the collection.

SyncRoot SyncRoot SyncRoot SyncRoot

Gets an object that can be used to synchronize access to the collection.

Methods

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

Copies all the elements of the collection to the given array starting at the given index.

CopyTo(Match[], Int32) CopyTo(Match[], Int32) CopyTo(Match[], Int32) CopyTo(Match[], Int32)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Provides an enumerator that iterates through the collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

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

Gets the Type of the current instance.

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

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)
ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized
ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot
ICollection<Match>.Add(Match) ICollection<Match>.Add(Match) ICollection<Match>.Add(Match) ICollection<Match>.Add(Match)
ICollection<Match>.Clear() ICollection<Match>.Clear() ICollection<Match>.Clear() ICollection<Match>.Clear()
ICollection<Match>.Contains(Match) ICollection<Match>.Contains(Match) ICollection<Match>.Contains(Match) ICollection<Match>.Contains(Match)
ICollection<Match>.Remove(Match) ICollection<Match>.Remove(Match) ICollection<Match>.Remove(Match) ICollection<Match>.Remove(Match)
IEnumerable<Match>.GetEnumerator() IEnumerable<Match>.GetEnumerator() IEnumerable<Match>.GetEnumerator() IEnumerable<Match>.GetEnumerator()
IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)
IList.Clear() IList.Clear() IList.Clear() IList.Clear()
IList.Contains(Object) IList.Contains(Object) IList.Contains(Object) IList.Contains(Object)
IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object)
IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object)
IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize
IList.Item[Int32] IList.Item[Int32] IList.Item[Int32] IList.Item[Int32]
IList.Remove(Object) IList.Remove(Object) IList.Remove(Object) IList.Remove(Object)
IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32)
IList<Match>.IndexOf(Match) IList<Match>.IndexOf(Match) IList<Match>.IndexOf(Match) IList<Match>.IndexOf(Match)
IList<Match>.Insert(Int32, Match) IList<Match>.Insert(Int32, Match) IList<Match>.Insert(Int32, Match) IList<Match>.Insert(Int32, Match)
IList<Match>.Item[Int32] IList<Match>.Item[Int32] IList<Match>.Item[Int32] IList<Match>.Item[Int32]
IList<Match>.RemoveAt(Int32) IList<Match>.RemoveAt(Int32) IList<Match>.RemoveAt(Int32) IList<Match>.RemoveAt(Int32)

Extension Methods

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to