2010-07-27 31 views
2

我對正則表達式沒有太多經驗,我想糾正它。我決定建立一個應用程序,需要一個目錄名,掃描所有文件(即都有一個連續增長的數字,但在其文件名有細微的區別,例如:episode01.mp4episode_02.mp4episod03.mp4episode04.rmvb等)使用正則表達式在文件名中找到一個數字

的應用應該掃描在目錄中找到每個文件名中的編號,並將文件與擴展名一起重命名爲通用格式(episode01.mp4,episode02.mp4,episode03.mp4, episode04.rmvb, episode04.rmvb等)。

我有下面的代碼:

在此代碼
Dictionary<string, string> renameDictionary = new Dictionary<string,string>(); 
DirectoryInfo dInfo = new DirectoryInfo(path); 
string newFormat = "Episode{0}.{1}"; 
Regex regex = new Regex(@".*?(?<no>\d+).*?\.(?<ext>.*)"); //look for a number(before .) aext: *(d+)*.* 
foreach (var file in dInfo.GetFiles()) 
{ 
    string fileName = file.Name; 
    var match = regex.Match(fileName); 
    if (match != null) 
    { 
    GroupCollection gc = match.Groups; 
    //Console.WriteLine("Number : {0}, Extension : {2} found in {1}.", gc["no"], fileName,gc["ext"]); 
    renameDictionary[fileName] = string.Format(newFormat, gc["no"], gc["ext"]); 
    } 
} 
foreach (var renamePair in renameDictionary) 
{ 
    Console.WriteLine("{0} will be renamed to {1}.", renamePair.Key, renamePair.Value); 
    //stuff for renaming here 
} 

的一個問題是,它也包括沒有在renameDictionary號文件。如果你能指出我應該注意的其他問題,這也會很有幫助。

PS:我假設文件名只包含對應於串行(沒有像cam7_0001.jpg

回答

1

這種簡單的解決辦法可能是使用Path.GetFileNameWithoutExtension獲取文件名,然後正則表達式\d+$拿到號碼號碼(或者Path.GetExtension\d+可以在任何地方獲得號碼)。

您也可以在單個實現這一替換:

Regex.Replace(fileName, @".*?(\d+).*(\.[^.]+)$", "Episode$1$2") 

這正則表達式是一個好一點,因爲它迫使擴展不包含點。

相關問題