Can I test if a regex is valid in C# without throwing exception

I think exceptions are OK in this case.

Just make sure to shortcircuit and eliminate the exceptions you can:

private static bool IsValidRegex(string pattern)
{
    if (string.IsNullOrWhiteSpace(pattern)) return false;

    try
    {
        Regex.Match("", pattern);
    }
    catch (ArgumentException)
    {
        return false;
    }

    return true;
}

As long as you catch very specific exceptions, just do the try/catch.

Exceptions are not evil if used correctly.


Not without a lot of work. Regex parsing can be pretty involved, and there's nothing public in the Framework to validate an expression.

System.Text.RegularExpressions.RegexNode.ScanRegex() looks to be the main function responsible for parsing an expression, but it's internal (and throws exceptions for any invalid syntax anyway). So you'd be required to reimplement the parse functionality - which would undoubtedly fail on edge cases or Framework updates.

I think just catching the ArgumentException is as good an idea as you're likely to have in this situation.

Tags:

C#

Regex