文件名通配符匹配的代码

Windows 下可以用 * ? 作为通配符对文件名或目录名进行匹配。程序中有时候需要做这样的匹配,但.Net framework 没有提供内置的函数来做这个匹配。我写了一个通过正则进行匹配的方法。

 private static bool WildcardMatch(string text, string pattern, bool ignoreCase)
    {
        if (string.IsNullOrEmpty(pattern))
        {
            return true;
        }

        if (string.IsNullOrEmpty(text))
        {
            foreach (char c in pattern)
            {
                if (c != '*')
                {
                    return false;
                }
            }

            return true;
        }

        string regex = "^" + Regex.Escape(pattern).
                           Replace(@"\*", ".*").
                           Replace(@"\?", ".") + "$";

        if (ignoreCase)
        {
            Match match = Regex.Match(text, regex, RegexOptions.IgnoreCase);

            return match.ToString() == text;
        }
        else
        {
            Match match = Regex.Match(text, regex);

            return match.ToString() == text;
        }
    }
原文地址:https://www.cnblogs.com/eaglet/p/2887002.html