C# - 正则表达式 - 根据特定命名模式匹配文件名

12

我的应用程序需要查找并处理符合特定命名惯例的文件,如下所示。

IABC_12345-0_YYYYMMDD_YYYYMMDD_HHMMSS.zip

我无法通过搜索模式轻松完成这个任务,因此我假设在使用更简单的通配符模式生成文件列表之后,需要执行类似于这样的操作。

RegEx re = new RegEx("blah");

foreach(FileInfo fi in Directory.GetFiles(path, "I*.zip"))
{
    if(re.IsMatch(fi.Name))
       //blah blah blah
}

这是最好的方法吗?如果是,我该如何编写正则表达式以匹配此文件格式?

3个回答

18
    string pattern = @"I[A-Z]{3}_\d{5}-\d_\d{8}_\d{8}_\d{6}\.zip";
    var matches = Directory.GetFiles(@"c:\temp")
        .Where(path => Regex.Match(path, pattern).Success);

    foreach (string file in matches)
        Console.WriteLine(file); // do something

可以通过使用 Regex.IsMatch(...) 而不是 Regex.Match(...).Success 来稍微改进。 - tigrou

7
这取决于您想要匹配这些名称的具体程度。以下是否足够具体:
I[A-Z]{3}_\d{5}-\d_\d{8}_\d{8}_\d{6}\.zip

?

Explanation:

I             // match an 'I'
[A-Z]{3}      // followed by three upper case letters
_             // followed by an underscore
\d{5}         // followed by five digits
-             // followed by a hyphen
\d            // followed by a single digit
_             // followed by an underscore
\d{8}         // followed by eight digits
_             // followed by an underscore
\d{8}         // followed by eight digits
_             // followed by an underscore
\d{6}         // followed by six digits
\.zip         // followed by '.zip'

但是,如果您有文件名称中包含无效日期或时间的文件,仅靠正则表达式可能无法实现,尤其是如果您的 DATE_DATE 部分指定了一个日期范围。您需要像我(和其他人)展示的一样匹配所有文件名,然后执行一些“常规”编程逻辑来过滤掉无效的文件。


2

如果您需要一个简单的正则表达式,可以匹配无效的时间格式(例如,hours=73等),您可以使用以下内容:

^I[A-Z]{3}_\d{5}-\d_\d{8}_\d{8}_\d{6}\.zip$

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接