eaglet

本博专注于基于微软技术的搜索相关技术
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

文件名通配符匹配的代码

Posted on 2013-01-31 14:36  eaglet  阅读(2462)  评论(3编辑  收藏  举报

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