glob pattern matching in .NET

后端 未结 14 1436
遇见更好的自我
遇见更好的自我 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:29

    I like my code a little more semantic, so I wrote this extension method:

    using System.Text.RegularExpressions;
    
    namespace Whatever
    {
        public static class StringExtensions
        {
            /// 
            /// Compares the string against a given pattern.
            /// 
            /// The string.
            /// The pattern to match, where "*" means any sequence of characters, and "?" means any single character.
            /// true if the string matches the given pattern; otherwise false.
            public static bool Like(this string str, string pattern)
            {
                return new Regex(
                    "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                    RegexOptions.IgnoreCase | RegexOptions.Singleline
                ).IsMatch(str);
            }
        }
    }
    

    (change the namespace and/or copy the extension method to your own string extensions class)

    Using this extension, you can write statements like this:

    if (File.Name.Like("*.jpg"))
    {
       ....
    }
    

    Just sugar to make your code a little more legible :-)

提交回复
热议问题