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

后端 未结 8 1879
挽巷
挽巷 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: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);
    }
    

提交回复
热议问题