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.




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

Leave a Reply

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