The Matches method is similar to the Match method, except that it returns information about all the matches, instead of a single match, found in the input string. It is equivalent to the following code:

The collection includes only successful matches and terminates at the first unsuccessful match.

The regular expression pattern for which the Regex.Matches(String, Int32) method searches is defined by the call to one of the Regex class constructors. For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.

The Matches method uses lazy evaluation to populate the returned MatchCollection object. Accessing such members of this collection as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. To take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and ForEach…Next in Visual Basic.

The following example uses the Match(String) method to find the first word in a sentence that ends in "es", and then calls the Matches(String, Int32) method to identify any additional words that end in "es".

using System;
using System.Text.RegularExpressions;
publicclass Example
{
publicstaticvoid Main()
{
string pattern = @"\b\w+es\b";
Regex rgx = new Regex(pattern);
string sentence = "Who writes these notes and uses our paper?";
// Get the first match.
Match match = rgx.Match(sentence);
if (match.Success) {
Console.WriteLine("Found first 'es' in '{0}' at position {1}",
match.Value, match.Index);
// Get any additional matches. foreach (Match m in rgx.Matches(sentence, match.Index + match.Length))
Console.WriteLine("Also found '{0}' at position {1}",
m.Value, m.Index);
}
}
}
// The example displays the following output: // Found first 'es' in 'writes' at position 4 // Also found 'notes' at position 17 // Also found 'uses' at position 27

The regular expression pattern \b\w+es\b is defined as shown in the following table.