代码之家  ›  专栏  ›  技术社区  ›  Scott Ivey

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

  •  1
  • Scott Ivey  · 技术社区  · 16 年前

    我有一个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;
    

    …我有什么建议可以让这个工作吗?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Daniel Brückner    16 年前

    如果只需要与所有正则表达式匹配的目录。

    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)));
    
        2
  •  2
  •   Adam Robinson    16 年前

    我不认为你所采取的方法正是你想要的。这将对照所有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 = directories.Where(d =>
        {
            foreach (string pattern in regexStrings)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(d.FullName, pattern))
                {
                    return true;
                }
            }
    
            return false;
        });
    
        3
  •  0
  •   JohnathanKong    16 年前

    在加入前缺少where关键字