
Regex.Matches returns multiple Match objects. It matches multiple instances of a pattern in a C# program. This method returns a MatchCollection. It is very useful for extracting patterns from an input string.
This C# program uses the Regex.Matches method. It extracts substrings based on patterns.

To start, this program includes the System.Text.RegularExpressions namespace. It uses an input string that contains several words: each one starts with the letter s. Next, we use Regex.Matches on this string. The pattern provided to Regex.Matches will only match words starting with the letter s, with one or more non-whitespace characters, and ending in a lowercase d.
Program that uses Regex.Matches method [C#]
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// Input string.
const string value = @"said shed see spear spread super";
// Get a collection of matches.
MatchCollection matches = Regex.Matches(value, @"s\w+d");
// Use foreach loop.
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
}
}
}
}
Output
Index=0, Value=said
Index=5, Value=shed
Index=20, Value=spread
Foreach loop. Next we see how to use the foreach-loop on the MatchCollection returned by Regex.Matches. To get at the individual pieces matched, we need to loop over the Captures collection. Finally, we can access the Value property to get the actual string. The Index property tells us the character position of the capture.
Foreach Loop Examples
The Regex.Matches method provides a way for you to match multiple times in a single input string. You can then loop over these matches and their individual captures to get all the results. Doing this sort of text processing would be more cumbersome if you were to use methods such as IndexOf and Split on the string type.
Regex Type