如果您使用GetFileNameWithoutExtension
,将不会有扩展名,因此,按'_'
进行拆分即可。然后,您可以使用.Last()
完成最后一部分。
string[] filenames_partial_distinct = Array.ConvertAll(
filenames,file => Path.GetFileNameWithoutExtension(file).Split('_').Last()
)
.Distinct()
.ToArray();
使用输入
string[] filenames = { "aaa_ab12345.txt","bbb_ab12345.txt","aaa_ac12345.txt","bbb_ac12345","aaa_bbb_ab12345.txt" };
您得到的结果
{ "ab12345","ac12345" }
仅当文件名以StringSplitOptions.RemoveEmptyEntries
结尾(扩展名之前)时,才需要_
。
,
您似乎正在寻找这样的东西:
string[] arr = filenames.Select(n => n.Substring(n.IndexOf("_") + 1,7)).Distinct().ToArray();
,
我通常将这样的问题推迟到regex。他们非常强大。这种方法还使您有机会发现意外情况并进行适当处理。
这里是一个粗略的例子,假设我理解您的要求:
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string MyMatcher(string filename)
{
// this pattern may need work depending on what you need - it says
// extract that pattern between the "()" which is 2 characters and
// 4 digits,exactly; and can be found in `Groups[1]`.
Regex r = new Regex(@".*_(\w{2}\d{4}).*",RegexOptions.IgnoreCase);
Match m = r.Match(filename);
return m.Success
? m.Groups[1].ToString()
: null; // what should happen here?
}
string[] filenames =
{
"aaa_ab12345.txt","aaa_bbb_ab12345.txt","ae12345.txt" // MyMatcher() return null for this - what should you do if this happens?
};
var results = filenames
.Select(MyMatcher)
.Distinct();
foreach (var result in results)
{
Console.WriteLine(result);
}
}
}
礼物:
ab1234
ac1234
这可以进一步完善,例如预编译的regex模式,封装在类中等等。
本文链接:https://www.f2er.com/2946162.html