Show all of the matches to a regular expression in a string in C#

When you click the Go button, the program uses the following code to display matches.

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 ir red.

When the form starts, its regular expression is "in|or|and" so it matches occurrences of "in," "or", and "and."

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.