The file name wildcard matching code

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Can use the * Windows? As a wildcard character to a file or directory name matching. Sometimes need to do the matching procedure, but the.Net framework does not provide built-in functions to do the matching. I wrote a matching is done by regular method.


复制代码

 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;
        }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Augustine at November 17, 2013 - 11:16 AM