C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pattern: This will only match words starting with the letter s, with one or more non-whitespace characters, and ending in a lowercase d.
Foreach: We use foreach on the MatchCollection, and then on the result of the Captures property.
ForeachTip: To access the individual pieces matched by the Regex, 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.
C# program that uses Regex.Matches method
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
Note: Doing this sort of text processing would be more cumbersome if you were to use methods such as IndexOf and Split.
IndexOfSplit