【问题标题】:How to find files according RegEx in C#如何在 C# 中根据 RegEx 查找文件
【发布时间】:2011-02-18 01:43:08
【问题描述】:

我需要获取某些驱动器上具有与特定模式匹配的路径的文件列表,例如 FA\d\d\d\d.xml,其中 \d 是数字 (0,1,2..9)。所以文件可以有 FA5423.xml 之类的名称。

这样做最有效的名称是什么?

【问题讨论】:

标签: c# regex file search


【解决方案1】:

您使用的是 C# 3 吗?

Regex reg = new Regex(@"^FA[0-9]{4}\.xml$");
var files = Directory.GetFiles(yourPath, "*.xml").Where(path => reg.IsMatch(path));

【讨论】:

【解决方案2】:

你可以这样做:

System.IO.Directory.GetFiles(@"C:\", "FA????.xml", SearchOption.AllDirectories);

然后从您的结果中迭代它们并根据您的正则表达式验证它们,即名称中的 ? 字符都是数字

【讨论】:

    【解决方案3】:

    使用 Directory API 查找 FA????.xml,并通过正则表达式过滤器运行结果列表:

    var fa = from f in Directory.GetFiles("FA????.xml")
             where Regex.Match(f, "FA\d\d\d\d\.xml")
             select f;
    

    【讨论】:

    • Regex.Match 不会返回 Match 对象而不是布尔值吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多