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


I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.

I can of course do a Regex.IsMatch() inside a try/catch and see if it blows up that way, but are there any smarter ways of doing it? Speed is not an issue as such, I just prefer to avoid throwing exceptions for no reason.

10/20/2008 2:48:24 PM

Accepted Answer

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

Exceptions are not evil if used correctly.

10/20/2008 2:51:17 PM

I think exceptions are OK in this case.

Here's what I put together:

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

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

    return true;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow