Make a string extension that determines whether a string matches a regular expression in C#

The StringExtensions class defines the Matches string extension method.

using System.Text.RegularExpressions;

namespace howto_string_match_regex
{
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 text's Matches method to tell 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.

   

 

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.