Csharp/C#教程:C# – Regex – 根据特定的命名模式匹配文件名分享


C# – Regex – 根据特定的命名模式匹配文件名

我有一个应用程序,需要查找并处理遵循非常具体的命名约定的文件,如下所示。

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 } 

这是最好的方法,如果是这样,我将如何形成一个正则表达式来匹配这种文件格式?

  string pattern = @"I[AZ]{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 

这取决于您希望如何匹配这些名称。 这是否足够具体:

 I[AZ]{3}_d{5}-d_d{8}_d{8}_d{6}.zip 

说明:

 I // match an 'I' [AZ]{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' 

但是,如果您的文件名称包含无效的日期或时间,则实际上不能单独使用regex,特别是如果您的DATE_DATE部分指定了日期范围。 您将必须匹配I(和其他)向您显示的所有文件名,然后执行一些“常规”编程逻辑来过滤掉无效的文件名。

对于一个简单的正则表达式,它也会匹配无效的时间规范(即小时= 73等),你可以使用这样的东西:

 ^I[AZ]{3}_d{5}-d_d{8}_d{8}_d{6}.zip$ 

RegexBuddy是一个花几块钱的好方法(如果你有一些花钱)。 它将帮助您开发,测试和调试您的正则表达式。 它甚至可以为您创建代码段。

RegexMagic (来自同一作者)甚至可以为您提供更多帮助:它可以帮助您从样本中创建正则表达式模式。 (我没试过,所以我不能说它是否好)。

上述就是C#学习教程:C# – Regex – 根据特定的命名模式匹配文件名分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1030310.html

(0)
上一篇 2022年1月13日
下一篇 2022年1月13日

精彩推荐