regex - 如何检查文件名是否与通配符模式匹配

标签 regex .net

我有一个通配符模式,可能是“*.txt”或“POS??.dat”。

我还有内存中的文件名列表,我需要将其与该模式进行比较。

我该如何做到这一点,请记住我需要与 IO.DirectoryInfo.GetFiles(pattern) 使用的语义完全相同。

编辑:盲目地将其翻译成正则表达式是行不通的。

最佳答案

我有一个完整的代码答案,95% 都像 FindFiles(string)

不存在的 5% 是 MSDN 的第二个注释中的短名称/长名称行为。此功能的文档。

如果您仍然想获得该行为,则必须完成输入数组中每个字符串的短名称的计算,然后将长名称添加到匹配集合中(如果长名称为长名称)或短名称与模式匹配。

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace FindFilesRegEx
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "hello.t", "HelLo.tx", "HeLLo.txt", "HeLLo.txtsjfhs", "HeLLo.tx.sdj", "hAlLo20984.txt" };
            string[] matches;
            matches = FindFilesEmulator("hello.tx", names);
            matches = FindFilesEmulator("H*o*.???", names);
            matches = FindFilesEmulator("hello.txt", names);
            matches = FindFilesEmulator("lskfjd30", names);
        }

        public string[] FindFilesEmulator(string pattern, string[] names)
        {
            List<string> matches = new List<string>();
            Regex regex = FindFilesPatternToRegex.Convert(pattern);
            foreach (string s in names)
            {
                if (regex.IsMatch(s))
                {
                    matches.Add(s);
                }
            }
            return matches.ToArray();
        }

        internal static class FindFilesPatternToRegex
        {
            private static Regex HasQuestionMarkRegEx   = new Regex(@"\?", RegexOptions.Compiled);
            private static Regex IllegalCharactersRegex  = new Regex("[" + @"\/:<>|" + "\"]", RegexOptions.Compiled);
            private static Regex CatchExtentionRegex    = new Regex(@"^\s*.+\.([^\.]+)\s*$", RegexOptions.Compiled);
            private static string NonDotCharacters      = @"[^.]*";
            public static Regex Convert(string pattern)
            {
                if (pattern == null)
                {
                    throw new ArgumentNullException();
                }
                pattern = pattern.Trim();
                if (pattern.Length == 0)
                {
                    throw new ArgumentException("Pattern is empty.");
                }
                if(IllegalCharactersRegex.IsMatch(pattern))
                {
                    throw new ArgumentException("Pattern contains illegal characters.");
                }
                bool hasExtension = CatchExtentionRegex.IsMatch(pattern);
                bool matchExact = false;
                if (HasQuestionMarkRegEx.IsMatch(pattern))
                {
                    matchExact = true;
                }
                else if(hasExtension)
                {
                    matchExact = CatchExtentionRegex.Match(pattern).Groups[1].Length != 3;
                }
                string regexString = Regex.Escape(pattern);
                regexString = "^" + Regex.Replace(regexString, @"\\\*", ".*");
                regexString = Regex.Replace(regexString, @"\\\?", ".");
                if(!matchExact && hasExtension)
                {
                    regexString += NonDotCharacters;
                }
                regexString += "$";
                Regex regex = new Regex(regexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                return regex;
            }
        }
    }
}

关于regex - 如何检查文件名是否与通配符模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/652037/

相关文章:

c# - 如何在托管代码中创建 Windows 安全描述符?

python - 从 HTML、CSS 和 JavaScript 中获取干净的字符串

regex - 如何在Ant 'ReplaceRegExp'任务中执行数学函数?

c# - 如何在使用 C# 和 .NET 4.5 的 resgen.exe 生成的 StronglyTypedClass 文件中公开构造函数 StringResources

c# - C# .NET 位图的最大分辨率是多少?

c# - 后退按钮到上一个局部 View

python - 缓存字符串列表转换为列表

java - 从字符串中删除 xml 版本标记

不以特定字符编译问题结束的正则表达式

c# - 在实体对象设计中处理 id