使用正则表达式列表查找匹配的目录
我有一个 IEnumerable
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;
关于如何让它发挥作用有什么建议吗?
I have an IEnumerable<DirectoryInfo> that I want to filter down using an array of regular expressions to find the potential matches. I've been trying to join my directory and regex strings using linq, but can't seem to get it right. Here's what I'm trying to do...
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;
... any suggestions on how I can get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想匹配所有正则表达式的目录。
如果您只想匹配至少一个正则表达式的目录。
If you only want directories that match all regular expressions.
If you only want directories that match at least one regular expressions.
无论如何,我认为您所采取的方法并不完全是您想要的。 这将根据所有正则表达式字符串检查名称,而不是在第一个匹配时短路。 此外,如果一个目录匹配多个模式,它会复制目录。
我想你想要这样的东西:
I don't think that the approach you're taking is exactly what you want anyhow. That will check the name against ALL regex strings, rather than short circuiting on the first match. Additionally, it would duplicate the directories if one matched more than one pattern.
I think you want something like:
您在连接前面缺少Where关键字
you are missing your Where keyword in front of the join