glob pattern matching in .NET

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

    If you want to avoid regular expressions this is a basic glob implementation:

    public static class Globber
    {
        public static bool Glob(this string value, string pattern)
        {
            int pos = 0;
    
            while (pattern.Length != pos)
            {
                switch (pattern[pos])
                {
                    case '?':
                        break;
    
                    case '*':
                        for (int i = value.Length; i >= pos; i--)
                        {
                            if (Glob(value.Substring(i), pattern.Substring(pos + 1)))
                            {
                                return true;
                            }
                        }
                        return false;
    
                    default:
                        if (value.Length == pos || char.ToUpper(pattern[pos]) != char.ToUpper(value[pos]))
                        {
                            return false;
                        }
                        break;
                }
    
                pos++;
            }
    
            return value.Length == pos;
        }
    }
    

    Use it like this:

    Assert.IsTrue("text.txt".Glob("*.txt"));
    

提交回复
热议问题