tags:

views:

1217

answers:

7

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.

A: 

I have a method to test whether a RegEx is valid, but it just wraps the regex in a Try/Catch. I'm not sure if there's a better way to do this, but I couldn't find one.

Jon Tackabury
+13  A: 

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

Exceptions are not evil if used correctly.

Robert
A: 

A malformed regex isn't the worst of reasons for an exception.

Unless you resign to a very limited subset of regex syntax - and then write a regex (or a parser) for that - I think you have no other way of testing if it is valid but to try to build a state machine from it and make it match something.

Tomalak
+1  A: 

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.

Mark Brackett
A: 

In .NET, unless you write your own regular expression parser (which I would strongly advise against), you're almost certainly going to need to wrap the creation of the new Regex object with a try/catch.

theraccoonbear
A: 

Depending on who the target is for this, I'd be very careful. It's not hard to construct regexes that can backtrack on themselves and eat a lot of CPU and memory -- they can be an effective Denial of Service vector.

clintp
Is there no "stack overflow" protection in the .NET regex parsing library? Can you give me an example that might give me trouble?
Mark S. Rasmussen
+1  A: 

I think exceptions are OK in this case.

Here's what I put together:

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

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

    return true;
}
Jeff Atwood