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

后端 未结 8 1833
挽巷
挽巷 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:54

    I think exceptions are OK in this case.

    Just make sure to shortcircuit and eliminate the exceptions you can:

    private static bool IsValidRegex(string pattern)
    {
        if (string.IsNullOrWhiteSpace(pattern)) return false;
    
        try
        {
            Regex.Match("", pattern);
        }
        catch (ArgumentException)
        {
            return false;
        }
    
        return true;
    }
    
    0 讨论(0)
  • 2020-12-03 13:54

    I've ever been use below function and have no problem with that. It uses exception and timeout both, but it's functional. Of course it works on .Net Framework >= 4.5.

        public static bool IsValidRegexPattern(string pattern, string testText = "", int maxSecondTimeOut = 20)
        {
            if (string.IsNullOrEmpty(pattern)) return false;
            Regex re = new Regex(pattern, RegexOptions.None, new TimeSpan(0, 0, maxSecondTimeOut));
            try { re.IsMatch(testText); }
            catch{ return false; } //ArgumentException or RegexMatchTimeoutException
            return true;
        }
    
    0 讨论(0)
提交回复
热议问题