gpt4 book ai didi

c# - 使用正则表达式在文件名中查找数字

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:09 28 4
gpt4 key购买 nike

我对正则表达式没有太多经验,我想纠正这一点。我决定构建一个采用目录名称的应用程序,扫描所有文件(所有文件的序列号都在递增,但文件名略有不同。示例:episode01.mp4episode_02.mp4, episod03.mp4, episode04.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)

最佳答案

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

您也可以在单个替换中实现此目的:

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

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

关于c# - 使用正则表达式在文件名中查找数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3342612/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com