使用正则表达式列表查找匹配的目录

使用正则表达式列表查找匹配的目录

问题描述:

我有一个IEnumerable <DirectoryInfo>我想使用正则表达式数组来筛选可能的匹配。我一直试图加入我的目录和正则表达式字符串使用linq,但似乎无法做到正确。这就是我想要做的...使用正则表达式列表查找匹配的目录

string[] regexStrings = ... // some regex match code here. 

// get all of the directories below some root that match my initial criteria. 
var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories) 
        where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0 
         && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories 
          || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files) 
        select d; 

// filter the list of all directories based on the strings in the regex array 
var filteredDirs = from d in directories 
        join s in regexStrings on Regex.IsMatch(d.FullName, s) // compiler doesn't like this line 
        select d; 

...有关如何让这个工作的任何建议?

如果你只是想匹配所有的正则表达式该目录。

var result = directories 
    .Where(d => regexStrings.All(s => Regex.IsMatch(d.FullName, s))); 

如果您只想要至少匹配一个正则表达式的目录。

var result = directories 
    .Where(d => regexStrings.Any(s => Regex.IsMatch(d.FullName, s))); 
+0

啊,Any()上的通话很好。我一直在忘记那些! – 2009-07-08 18:42:03

你缺少你在哪里前面关键字加入

我不认为你正在服用的方法是你想反正什么。这将检查所有正则表达式字符串的名称,而不是在第一场比赛中短路。此外,如果一个模式匹配多个模式,它将复制目录。

我想你想要的东西,如:

string[] regexStrings = ... // some regex match code here. 

// get all of the directories below some root that match my initial criteria. 
var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories) 
        where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0 
         && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories 
          || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files) 
        select d; 

// filter the list of all directories based on the strings in the regex array 
var filteredDirs = directories.Where(d => 
    { 
     foreach (string pattern in regexStrings) 
     { 
      if (System.Text.RegularExpressions.Regex.IsMatch(d.FullName, pattern)) 
      { 
       return true; 
      } 
     } 

     return false; 
    }); 
+0

+1好答案。 – 2009-07-08 18:44:59