Can I test if a regex is valid in C# without throwing exception

后端 未结 8 1832
挽巷
挽巷 2020-12-03 13:19

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 expression

相关标签:
8条回答
  • 2020-12-03 13:39

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

    Exceptions are not evil if used correctly.

    0 讨论(0)
  • 2020-12-03 13:40

    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.

    0 讨论(0)
  • 2020-12-03 13:41

    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.

    0 讨论(0)
  • 2020-12-03 13:42

    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.

    0 讨论(0)
  • 2020-12-03 13:50

    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.

    0 讨论(0)
  • 2020-12-03 13:53

    By using following method you can check wether your reguler expression is valid or not. here testPattern is the pattern you have to check.

    public static bool VerifyRegEx(string testPattern)
    {
        bool isValid = true;
        if ((testPattern != null) && (testPattern.Trim().Length > 0))
        {
            try
            {
                Regex.Match("", testPattern);
            }
            catch (ArgumentException)
            {
                // BAD PATTERN: Syntax error
                isValid = false;
            }
        }
        else
        {
            //BAD PATTERN: Pattern is null or blank
            isValid = false;
        }
        return (isValid);
    }
    
    0 讨论(0)
提交回复
热议问题