Title: Show regular expression matches in C#
When you click the Go button, the program uses the following code to display regular expression matches in a string.
Regex reg_exp = new Regex(txtPattern.Text);
MatchCollection matches = reg_exp.Matches(txtTestString.Text);
rchResults.Text = txtTestString.Text;
foreach (Match a_match in matches)
{
rchResults.Select(a_match.Index, a_match.Length);
rchResults.SelectionColor = Color.Red;
}
The code creates a Regex object, passing it the regular expression that you want to use for matching. It then invokes the object's Matches method to get a collection of Match objects that represent the places in the test string that match the regular expression.
The code then copies the test string into the result RichTextBox and loops through the collection of matches. For each match, the program selects the matched part of the test string in the RichTextBox and makes it red.
When the form starts, its regular expression is "in|or|and" so it matches occurrences of "in," "or", and "and" within the test string.
Download the example to experiment with it and to see additional details.
|