O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.3. Verifying the Syntax of a Regular Expression

Problem

You have either constructed a regular expression dynamically from your code or based on user input. You need to test the validity of this regular expression’s syntax before you actually use it.

Solution

Use the following method to test the validity of a regular expression’s syntax:

using System;
using System.Text.RegularExpressions;

public static bool VerifyRegEx(string testPattern)
{
    bool isValid = true;

    if ((testPattern != null) && (testPattern.Trim( ).Length > 0))
    {
        try
        {
            Regex.Match("", testPattern);
        }
        catch (ArgumentException)
        {
            // BAD PATTERN: Syntax error
            isValid = false;
        }
    }
    else
    {
        //BAD PATTERN: Pattern is null or blank
        isValid = false;
    }

    return (isValid);
}

To use this method, pass it the regular expression that you wish to verify:

public static void TestUserInputRegEx(string regEx)
{
    if (VerifyRegEx(regEx))
        Console.WriteLine("This is a valid regular expression.");
    else
        Console.WriteLine("This is not a valid regular expression.");
}

Discussion

The VerifyRegEx method calls the static Regex.Match method, which is useful for running quick regular expressions against a string. The static Regex.Match method returns a single Match object. By using this static method to run a regular expression against a string (in this case a blank string), we can determine whether the regular expression is invalid by watching for a thrown exception. The Regex.Match method will throw an ArgumentException if the regular expression is not syntactically ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required