代码之家  ›  专栏  ›  技术社区  ›  Mark S. Rasmussen

我可以测试正则表达式在C#中是否有效而不引发异常吗

  •  43
  • Mark S. Rasmussen  · 技术社区  · 17 年前

    8 回复  |  直到 17 年前
        1
  •  59
  •   Shimmy Weitzhandler 500 - Internal Server Error    5 年前

    只要确保短路并消除异常即可:

    private static bool IsValidRegex(string pattern)
    {
        if (string.IsNullOrWhiteSpace(pattern)) return false;
    
        try
        {
            Regex.Match("", pattern);
        }
        catch (ArgumentException)
        {
            return false;
        }
    
        return true;
    }
    
        2
  •  41
  •   Robert Deml    17 年前

        3
  •  7
  •   Liam Joshua    5 年前

    不是没有很多工作。正则表达式解析可能非常复杂,并且框架中没有任何公共内容可用于验证表达式。

    System.Text.RegularExpressions.RegexNode.ScanRegex() 看起来是负责解析表达式的主函数,但它是内部函数(并对任何无效语法抛出异常)。因此,您需要重新实现解析功能——这无疑会在边缘案例或框架更新中失败。

    我认为,在这种情况下,抓住这个例外是一个很好的主意。

        4
  •  3
  •   MiMFa    6 年前

    当然,它可以在.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;
        }
    
        5
  •  2
  •   Tomalak    17 年前

    格式错误的正则表达式并不是导致异常的最糟糕原因。

    除非你辞职 非常

        6
  •  2
  •   Clinton Pierce    17 年前

    这取决于目标是谁,我会非常小心。不难构造能够自行回溯并消耗大量CPU和内存的正则表达式——它们可能是有效的拒绝服务向量。

        7
  •  0
  •   theraccoonbear    17 年前

    在.NET中,除非您编写自己的正则表达式解析器(我强烈建议您不要这样做),否则几乎肯定需要用try/catch来包装新Regex对象的创建。

        8
  •  -3
  •   Alex    12 年前

    通过使用以下方法,您可以检查正则表达式是否有效。这里testPattern是您必须检查的模式。

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