[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.