Actualización: noviembre 2007
Representa el conjunto de coincidencias con éxito encontradas por la solicitud iterada de un modelo de expresión regular en la cadena de entrada.
Espacio de nombres:
System.Text.RegularExpressions
Ensamblado:
System (en System.dll)
Visual Basic (Declaración)
<SerializableAttribute> _
Public Class MatchCollection _
Implements ICollection, IEnumerable
Dim instance As MatchCollection
[SerializableAttribute]
public class MatchCollection : ICollection,
IEnumerable
[SerializableAttribute]
public ref class MatchCollection : ICollection,
IEnumerable
/** @attribute SerializableAttribute */
public class MatchCollection implements ICollection,
IEnumerable
public class MatchCollection implements ICollection, IEnumerable
La colección es inmutable (de sólo lectura) y no tiene constructor público. El método Regex..::.Matches devuelve un objeto MatchCollection.
Al aplicar un modelo de expresión regular a una cadena de entrada determinada, el motor de expresiones regulares utiliza cualquiera de las dos técnicas para generar el objeto MatchCollection:
Evaluación directa.
El objeto MatchCollection se rellena de una sola vez con todas las coincidencias resultantes de una llamada concreta al método Regex..::.Matches. Esta técnica se utiliza cuando se obtiene acceso a la propiedad Count de la colección. Suele ser el método más caro para rellenar la colección e implica una mayor disminución del rendimiento.
Evaluación lenta.
El objeto MatchCollection se rellena según sea necesario coincidencia por coincidencia. Equivale a repetidas llamadas por parte del motor de expresiones regulares al método Regex..::.Match y la adición de cada coincidencia a la colección. Esta técnica se utiliza cuando se obtiene acceso a la colección a través de su método GetEnumerator, o bien, cuando se obtiene acceso mediante la instrucción foreach (en C#) o la instrucción For Each ...Next (en Visual Basic).
El código de ejemplo siguiente ilustra la utilización de la clase MatchCollection para interrogar un conjunto de instancias Match.
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 jumped 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 jumped 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
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 jumped 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 jumped 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
#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 jumped 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);
}
}
import System.*;
import System.Text.RegularExpressions.*;
public class Test
{
public static void main(String[] args)
{
// 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 jumped over the "
+ "lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found.", (Int32)matches.get_Count());
// Report on each match.
for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) {
Match match = matches.get_Item(iCtr);
String word = match.get_Groups().get_Item("word").get_Value();
int index = match.get_Index();
Console.WriteLine("{0} repeated at position {1}", word,
(Int32)index);
}
} //main
} //Test
System..::.Object
System.Text.RegularExpressions..::.MatchCollection
Seguridad para subprocesos
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
.NET Framework
Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0
.NET Compact Framework
Compatible con: 3.5, 2.0, 1.0
XNA Framework
Compatible con: 2.0, 1.0
Referencia