glob pattern matching in .NET

后端 未结 14 1440
遇见更好的自我
遇见更好的自我 2020-11-29 01:52

Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I\'d like to match using UNIX style (glob) wildcards (* = any number of any characte

14条回答
  •  半阙折子戏
    2020-11-29 02:13

    Based on previous posts, I threw together a C# class:

    using System;
    using System.Text.RegularExpressions;
    
    public class FileWildcard
    {
        Regex mRegex;
    
        public FileWildcard(string wildcard)
        {
            string pattern = string.Format("^{0}$", Regex.Escape(wildcard)
                .Replace(@"\*", ".*").Replace(@"\?", "."));
            mRegex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }
        public bool IsMatch(string filenameToCompare)
        {
            return mRegex.IsMatch(filenameToCompare);
        }
    }
    

    Using it would go something like this:

    FileWildcard w = new FileWildcard("*.txt");
    if (w.IsMatch("Doug.Txt"))
       Console.WriteLine("We have a match");
    

    The matching is NOT the same as the System.IO.Directory.GetFiles() method, so don't use them together.

提交回复
热议问题