tags:

views:

147

answers:

1

I'm developing an application in .NET where the user can provide Regular Expressions that are afterwards used to validate input data.

I need a way to know if a regular expression is actually valid for the .net regex engine.

Thanks for any help

+8  A: 

Just try to compile the given regex. You can do that by creating the Regex object and passing the pattern to it. Here's a sample code:

public static bool IsRegexPatternValid(String pattern)
{
    try
    {
        new Regex(pattern);
        return true;
    }
    catch { }
    return false;
}
Paulius Maruška
That's the approach I'm currently using. The issue is that I'm using a try{} catch{} block. I wanted to know if there is a non-exception way of doing this. Thanks nevertheless
Kiranu
It is just the way Regex class is designed in .NET - to check if a pattern is valid, you need to compile it and see if any exceptions are thrown. I never heard of any other way of doing this.
Paulius Maruška
@Paulius: I decided to delete my answer since they're not very different and it doesn't add anything extra at this point. No sense in duplication :)
Ahmad Mageed
@Ahmad: Yeah, and I decided to add a code snippet to illustrate what I mean. :)
Paulius Maruška