给定目录树,根文件夹名称为“rootuploaded”,我需要使用以下规则将此树中的文件组合成一些组:
根据6种命名约定(自上而下优先级)对文件进行分组:
以下是程序输入和输出的简单示例:
输入是一个目录树,如下所示:
输出:
第1组
rootuploaded\samplefolder\1232_234234_1.jpg
rootuploaded\samplefolder\1232_234234_2.bmp
第2组
rootuploaded\file1.txt
rootuploaded\file2.txt
rootuploaded\file5.txt
第3组
rootuploaded\file-5.txt
rootuploaded\file-67.txt
第4组
rootuploaded\file_sample.txt
rootuploaded\file_sample_a.txt
无法分组
rootuploaded\samplefolder\1232_2342.jpg
rootuploaded\file-a.txt
rootuploaded\filea.txt
答案 0 :(得分:0)
使用正则表达式进行分组。 Linq的方法GroupBy
和Take
可能对其他方法有所帮助。
答案 1 :(得分:0)
以下是一些不使用Linq的示例代码。 CreateGroups
将返回列表列表。每个外部列表都匹配特定的正则表达式。内部列表中的项是与正则表达式匹配的输入。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class Test
{
public string[] TestInput = new string[]
{
@"rootuploaded\samplefolder\1232_234234_1.jpg",
@"rootuploaded\samplefolder\1232_234234_2.bmp",
@"rootuploaded\file-5.txt",
@"rootuploaded\file-67.txt",
@"rootuploaded\file-a.txt",
@"rootuploaded\file1.txt",
@"rootuploaded\file2.txt",
@"rootuploaded\file5.txt",
@"rootuploaded\filea.txt",
@"rootuploaded\file_sample.txt",
@"rootuploaded\file_sample_a.txt"
};
public string[] RegularExpressions = new string[]
{
"[A-Za-z_]+",
"[A-Za-z-]+",
"[A-Za-z]+_[0-9]+",
"[A-Za-z]+-[0-9]+",
"[A-Za-z]+ [0-9]+",
"[A-Za-z]+[0-9]+"
};
public List<List<string>> CreateGroups(string[] inputs)
{
List<List<string>> output = new List<List<string>>(RegularExpressions.Length);
for (int i = 0; i < RegularExpressions.Length; ++i)
output.Add(new List<string>());
foreach (string input in inputs)
{
string filename = Path.GetFileNameWithoutExtension(input);
for (int i = 0; i < RegularExpressions.Length; ++i)
{
Match match = Regex.Match(filename, RegularExpressions[i]);
if (match.Success && match.Length == filename.Length)
{
output[i].Add(input);
break;
}
}
}
return output;
}
}
显示结果的示例:
Test test = new Test();
var output = test.CreateGroups(test.TestInput);
foreach (List<string> list in output)
{
string group = "Group:\r\n";
foreach (string item in list)
group += "\t" + item + "\r\n";
Console.WriteLine(group);
}