【问题标题】:Find files with matching patterns in a directory c#?在目录c#中查找具有匹配模式的文件?
【发布时间】:2012-06-05 07:29:51
【问题描述】:
 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 中操纵这些模式。

谁能帮帮我?

【问题讨论】:

    标签: c# .net regex io


    【解决方案1】:

    您可以在 regex 中放置 OR

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

    【讨论】:

      【解决方案2】:

      改变

       .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 了解更多信息。

      【讨论】:

      • 应该是 Regex.Match(System.IO.File.GetFileName(path), pattern),因为 GetFileNames 返回完整路径。
      【解决方案3】:

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

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

      【讨论】:

      • 这是非常低效的,因为 Directory.GetFiles() 调用将在每个模式中执行一次。如果您反转操作会更好: Directory.GetFiles(...).SelectMany(file => patterns)... 但是如果恰好匹配两个表达式,这两个都会返回相同的文件两次。请参阅我的答案以获取不这样做的解决方案,因此效率更高(只要一个模式匹配,它就会停止匹配)
      • 确实 - 使用正则表达式是迄今为止最好的解决方案 - 正如已经提到的 :)
      【解决方案4】:

      你可以做的最简单的例子

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

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

      Regex 类可用模式的参考可以是found here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-04
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多