[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Make a string extension to determine whether a string matches a regular expression in C#

Regular expressions let you (relatively) easily determine whether a string matches some sort of pattern. This example shows how to make a string extension method to determine whether a string matches a regular expression in C#

The following StringExtensions class defines the Matches string extension method.

public static class StringExtensions { // Extension to add a Matches method to the string class. public static bool Matches(this string the_string, string pattern) { Regex reg_exp = new Regex(pattern); return reg_exp.IsMatch(the_string); } }

The extension method creates a Regex object and uses its IsMatch method to determine whether the string matches the expression.

The main program uses the extension method as in the following code.

// Validate a 7-digit US phone number. private void txt7Digit_TextChanged(object sender, EventArgs e) { if (txt7Digit.Text.Matches("^[2-9]{3}-\\d{4}$")) { txt7Digit.BackColor = Color.White; } else { txt7Digit.BackColor = Color.Yellow; } }

When the user changes the text in the txt7Digit TextBox, the code uses the Matches extension method to determine whether the user has entered a valid 7-digit US phone number. It sets the TextBox's background color to yellow if the text doesn't match and sets it to white if the text does match.

The program uses two other TextBoxes that determine whether they contain a 10-digit US phone number, and either a 7- or 10-digit phone number.

Download the example to experiment with it and to see additional details.

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