20

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

Carlos G.
  • 4,564
  • 4
  • 34
  • 57

1 Answers1

34

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
  • 5,790
  • 7
  • 42
  • 47
  • 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 – Carlos G. Sep 03 '09 at 04:21
  • 2
    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 Sep 03 '09 at 04:30
  • 1
    Ugh this sucks hard if you're using it as a dynamic filter over a large collection :( – Sinaesthetic Dec 30 '15 at 02:00