使用正则表达式获取多种指定扩展名的文件

 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

posted @ 2019-05-03 13:23  落樱的凄美  阅读(3918)  评论(0编辑  收藏  举报