MatchCollection 类

定义

表示通过以迭代方式将正则表达式模式应用于输入字符串所找到的成功匹配的集合。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
[System.Serializable]
public class MatchCollection : System.Collections.ICollection
type MatchCollection = class
    interface ICollection
    interface IEnumerable
Public Class MatchCollection
Implements ICollection
继承
MatchCollection
属性
实现

示例

下面的示例演示如何使用MatchCollection类来询问一Match组实例。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.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

注解

该集合是不可变的 (只读), 没有公共构造函数。The collection is immutable (read-only) and has no public constructor. Regex.Matches 方法返回 MatchCollection 对象。The Regex.Matches method returns a MatchCollection object.

集合包含零个或多System.Text.RegularExpressions.Match个对象。The collection contains zero or more System.Text.RegularExpressions.Match objects. 如果匹配成功, 则为输入字符串中找到的每System.Text.RegularExpressions.Match个匹配项填充集合。If the match is successful, the collection is populated with one System.Text.RegularExpressions.Match object for each match found in the input string. 如果匹配不成功, 则集合不包含任何System.Text.RegularExpressions.Match对象, 其Count属性等于零。If the match is unsuccessful, the collection contains no System.Text.RegularExpressions.Match objects, and its Count property equals zero.

在将正则表达式模式应用于特定输入字符串时, 正则表达式引擎使用以下两种方法之一来MatchCollection生成对象: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.

    完全填充Regex.Matches对象, 其中的所有匹配项都是对方法的特定调用所导致的。 MatchCollectionThe MatchCollection object is populated all at once, with all matches resulting from a particular call to the Regex.Matches method. 当访问集合的Count属性时, 将使用此方法。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.

    MatchCollection对象根据需要按匹配项进行填充。The MatchCollection object is populated as needed on a match-by-match basis. 它等效于调用Regex.Match方法的正则表达式引擎, 并向集合添加每个匹配项。It is equivalent to the regular expression engine calling the Regex.Match method repeatedly and adding each match to the collection. 当通过其GetEnumerator方法访问集合时, 或foreach使用语句C# For Each(在中) 或 ... 的情况下访问该集合时, 将使用此方法。Next语句 (Visual Basic)。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).

若要循环访问集合的成员, 应使用语言提供的集合迭代构造 (如foreach For Each C#和 .NextTo 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 在 Visual Basic 中), 而不是检索GetEnumerator方法返回的枚举器。in Visual Basic) instead of retrieving the enumerator that is returned by the GetEnumerator method.

属性

Count

获取匹配项的数目。Gets the number of matches.

IsReadOnly

获取一个值,指示集合是否为只读集合。Gets a value that indicates whether the collection is read only.

IsSynchronized

获取一个值,该值指示对集合的访问是否为同步的(线程安全)。Gets a value indicating whether access to the collection is synchronized (thread-safe).

Item[Int32]

获取该集合的单个成员。Gets an individual member of the collection.

SyncRoot

获取可用于同步对集合的访问的对象。Gets an object that can be used to synchronize access to the collection.

方法

CopyTo(Array, Int32)

从给定索引处开始将集合的所有元素复制到给定数组。Copies all the elements of the collection to the given array starting at the given index.

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

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnumerator()

提供一个循环访问集合的枚举器。Provides an enumerator that iterates through the collection.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

ICollection.CopyTo(Array, Int32)

从指定索引处开始,将集合中的所有元素复制到指定的数组。Copies all the elements of the collection to the specified array starting at the specified index.

ICollection.IsSynchronized

获取一个值,该值指示对集合的访问是否同步(线程安全)。Gets a value that indicates whether access to the collection is synchronized (thread-safe).

ICollection.SyncRoot

获取可用于同步对集合的访问的对象。Gets an object that can be used to synchronize access to the collection.

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

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于