How do I check if a filename matches a wildcard pattern

前端 未结 8 1575
青春惊慌失措
青春惊慌失措 2020-11-30 06:16

I\'ve got a wildcard pattern, perhaps \"*.txt\" or \"POS??.dat\".

I also have list of filenames in memory that I need to compare to that pattern.

How would

8条回答
  •  悲&欢浪女
    2020-11-30 07:01

    The use of RegexOptions.IgnoreCase will fix it.

    public class WildcardPattern : Regex {
        public WildcardPattern(string wildCardPattern)
            : base(ConvertPatternToRegex(wildCardPattern), RegexOptions.IgnoreCase) {
        }
    
        public WildcardPattern(string wildcardPattern, RegexOptions regexOptions)
            : base(ConvertPatternToRegex(wildcardPattern), regexOptions) {
        }
    
        private static string ConvertPatternToRegex(string wildcardPattern) {
            string patternWithWildcards = Regex.Escape(wildcardPattern).Replace("\\*", ".*");
            patternWithWildcards = string.Concat("^", patternWithWildcards.Replace("\\?", "."), "$");
            return patternWithWildcards;
        }
    }
    

提交回复
热议问题