Kees C. Bakker
Kees C. Bakker

Reputation: 33431

How to validate if the input contains a valid .Net regular expression?

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

Upvotes: 6

Views: 630

Answers (2)

Davio
Davio

Reputation: 4737

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;
        }
    }
}

Upvotes: 2

Euphoric
Euphoric

Reputation: 12849

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.

Upvotes: 7

Related Questions