繁体   English   中英

在目录c#中查找具有匹配模式的文件?

[英]Find files with matching patterns in a directory c#?

 string fileName = "";

            string sourcePath = @"C:\vish";
            string targetPath = @"C:\SR";

            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            string pattern = @"23456780";
            var matches = Directory.GetFiles(@"c:\vish")
                .Where(path => Regex.Match(path, pattern).Success);

            foreach (string file in matches)
            {
                Console.WriteLine(file); 
                fileName = System.IO.Path.GetFileName(file);
                Console.WriteLine(fileName);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(file, destFile, true);

            }

我的上述程序适用于单一模式。

我正在使用上面的程序来查找具有匹配模式的目录中的文件但在我的情况下我有多个模式所以我需要将string pattern变量中的多个模式作为数组传递但我不知道我是怎么回事可以在Regex.Match中操纵这些模式。

谁能帮我?

你可以在正则表达式中加一个OR

string pattern = @"(23456780|otherpatt)";

更改

 .Where(path => Regex.Match(path, pattern).Success);

 .Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success));

其中patterns是IEnumerable<string> ,例如:

 string[] patterns = { "123", "456", "789" };

如果阵列中有超过15个表达式,则可能需要增加缓存大小:

 Regex.CacheSize = Math.Max(Regex.CacheSize, patterns.Length);

有关更多信息,请参阅http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx

Aleroot的答案是最好的,但是如果你想在你的代码中做到这一点,你也可以这样做:

   string[] patterns = new string[] { "23456780", "anotherpattern"};
        var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish")
            .Where(path => Regex.Match(path, pat).Success));

例如,您可以使用最简单的形式

string pattern = @"(23456780|abc|\.doc$)";

这将匹配您选择的模式或具有abc模式的文件或扩展名为.doc的文件

可以在此处找到可用于Regex类的模式的参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM