2009-07-08 2 views
1

나는 잠재적 인 일치 항목을 찾기 위해 정규식 배열을 사용하여 필터링 할 IEnumerable <DirectoryInfo>을 가지고 있습니다. 나는 linq을 사용하여 나의 디렉토리와 regex 문자열에 합류하려고 노력해 왔지만 그것을 올바르게 얻는 것처럼 보이지 않는다. 여기에 내가 뭘하려고하는지 ...정규식 목록을 사용하여 일치하는 디렉터리 찾기

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; 

... 내가 어떻게 작동하도록 할 수있는 제안?

답변

4

:

난 당신이 뭔가를하려는 생각합니다.

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() 호출이 좋습니다. 나는 그 사람들에 대해 잊고있다! –

+0

Doh! - 나는 그 모든 것을 잊어 버린다. –

0

당신이없는 사용자의 경우 앞에 키워드 조인

2

난 당신이 복용하고있는 방법은 당신이 어쨌든 원하는 정확히 무엇이라고 생각하지 않습니다. 그 첫 번째 일치 짧은 회로보다는 모든 정규식 문자열에 대해 이름을 확인합니다. 또한 하나 이상의 패턴과 일치하는 경우 디렉토리를 복제합니다. 당신은 모든 정규 표현식과 일치하는 디렉토리를 원하는 경우

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 좋은 답변입니다. –

관련 문제