【问题标题】:finding a number in filename using regex使用正则表达式在文件名中查找数字
【发布时间】:2010-07-27 10:20:49
【问题描述】:

我对正则表达式没有太多经验,我想纠正这一点。我决定构建一个应用程序,它采用目录名称,扫描所有文件(所有文件的序列号都在增加,但文件名略有不同。例如:episode01.mp4episode_02.mp4episod03.mp4episode04.rmvb 等)

应用程序应扫描目录,找到每个文件名中的编号,并将文件连同扩展名一起重命名为通用格式(episode01.mp4episode02.mp4episode03.mp4episode04.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

【问题讨论】:

    标签: c# regex filenames


    【解决方案1】:

    这个最简单的解决方案可能是使用Path.GetFileNameWithoutExtension 来获取文件名,然后使用正则表达式\d+$ 来获取其末尾的数字(或Path.GetExtension\d+ 来获取任何地方的数字)。

    您也可以通过一次替换来实现:

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

    这个正则表达式更好一点,因为它强制扩展不包含点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多