Show regular expression matches in C#


regular expression matches

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in regular expressions, strings and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *