使用正则表达式获取多种指定扩展名的文件
static void TestFile()
{
string[] extends = {@"\.png",@"\.jpg" };
string pattern = string.Join("|",extends);
pattern = string.Format("({0})$",pattern);
Regex regex = new Regex(@pattern);
string[] names = {
"D:\\Text\\01.txt","D:\\Text\\01png","D:\\Text\\01pngasda",
"D:\\Textures\\awsl.jpg","D:\\Textures\\asdad.psd","D:\\Textures\\eee.png",
"C:\\Textures\\as.jpg", "D:\\Textures\\asjdia.jepg" };
foreach (string name in names)
{
if (regex.IsMatch(name))
{
Console.WriteLine(name);
}
}
}
将输入的文件后缀组合成正则表达式,然后验证测试数组
得到结果
D:\Textures\awsl.jpg
D:\Textures\eee.png
C:\Textures\as.jpg