5

I'm building an application that saves named regular expressions into a database. Looks like this:

Regex form

I'm using Asp.Net forms. How can I validate the entered regex? It would like the user to know if the entered regex is not a valid .Net regular expression.

The field should reject values like:

^Wrong(R[g[x)]]$
Invalid\Q&\A
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • Interesting question. Looking at this post it's impossible: http://stackoverflow.com/questions/2789407/regular-expression-for-regular-expressions – Dan Fox Oct 26 '12 at 10:05
  • That's very hard as basically anything is a Regex, it's just that incorrect Regexes won't match anything. You could provide a testbox where users can enter something to match and you can test the entered Regex against this test input. – Davio Oct 26 '12 at 10:06
  • @DanFox, the validation doesn't have to be done by regular expression, especially if that's impossible. – Kees C. Bakker Oct 26 '12 at 10:06
  • 2
    @Davio: that's not true. something like `(` is not a valid regex because there is no matching close bracket. It would need to be escaped to be valid. Obviously there are other constructs in regex that are "special" that would cause it to be invalid. – Chris Oct 26 '12 at 10:11
  • On the Regex validating Regex topic - this one rulez: http://stackoverflow.com/questions/172303/is-there-a-regular-expression-to-detect-a-valid-regular-expression – Kees C. Bakker Oct 26 '12 at 10:39

2 Answers2

6

Make new Regex class out of it. If it throws exception, then it is invalid.

try{
  new Regex(expression)
}
catch(ArgumentException ex)
{
  // invalid regex
}

// valid regex

I know. Using exceptions for code logic is wrong. But this seems to be only solution.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • 1
    Nah, using Exceptions is OK for a case like this. You could wrap it in a custom TryParse method. – Davio Oct 26 '12 at 10:10
  • Maybe somebody should write a regular expression to validate regular expressions... ;-) – Chris Oct 26 '12 at 10:12
  • @Chris Thats not mathematically possible. – Euphoric Oct 26 '12 at 10:14
  • It was a joke. I was pretty sure that regex syntax wouldn't be regular enough (though I have never actually seen a proof so would be interested to see one). – Chris Oct 29 '12 at 11:06
2

Something like this perhaps:

public static class RegexUtils
{

    public static bool TryParse (string possibleRegex, out Regex regex)
    {
        regex = null;
        try
        {
            regex = new Regex(possibleRegex);
            return true;
        }
        catch (ArgumentException ae)
        {
           return false;
        }
    }
}
Davio
  • 4,609
  • 2
  • 31
  • 58