我有一个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;
...关于如何让这个工作的任何建议?
答案 0 :(得分: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)));
答案 1 :(得分: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;
});
答案 2 :(得分:0)
您在联接前缺少Where关键字