www.gibmonks.com

Table of Contents




Previous Page
Next Page

Recipe 10.3. Verifying the Syntax of a Regular Expression

Problem

You have constructed a regular expression dynamically, either 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 VerifyRegEx method shown in Example 10-4 to test the validity of a regular expression's syntax.

Example 10-4. VerifyRegEx method

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 regular expressions on the fly 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), you 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 correct. The Message property of this exception contains the reason the regular expression failed to run, and the ParamName property contains the regular expression passed to the Match method. Both of these properties are read-only.

Before testing the regular expression with the static Match method, the regular expression is tested to see if it is null or blank. A null regular expression string returns an ArgumentNullException when passed in to the Match method. On the other hand, if a blank regular expression is passed in to the Match method, no exception is thrown (as long as a valid string is also passed to the first parameter of the Match method).


Previous Page
Next Page