簡體   English   中英

C# - Regex - 根據特定的命名模式匹配文件名

[英]C# - Regex - Matching file names according to a specific naming pattern

我有一個應用程序需要查找並處理遵循非常具體的命名約定的文件,如下所示。

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[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

這取決於您希望如何匹配這些名稱。 這是否足夠具體:

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

說明:

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'

但是,如果您的文件名稱包含無效的日期或時間,則實際上不能單獨使用regex,特別是如果您的DATE_DATE部分指定了日期范圍。 您將必須匹配I(和其他)向您展示的所有文件名,然后執行一些“常規”編程邏輯來過濾掉無效的文件名。

對於一個簡單的正則表達式,它也會匹配無效的時間規范(即小時= 73等),你可以使用這樣的東西:

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

RegexBuddy是一個花幾塊錢的好方法(如果你有一些花錢)。 它將幫助您開發,測試和調試您的正則表達式。 它甚至可以為您創建代碼段。

RegexMagic (來自同一作者)甚至可以為您提供更多幫助:它可以幫助您從樣本創建正則表達式模式。 (我沒試過,所以我不能說它是否好)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM