正则表达式有条件地解析出文件名和部分路径
我有一个 C# 应用程序,它使用搜索功能查找目录中的所有文件,然后将它们显示在列表中。我需要能够根据扩展名(可以使用搜索功能)和目录(例如,阻止“测试”或“调试”目录中的任何文件显示)来过滤文件。
我当前的代码是这样的:(
Regex filter = new Regex(@"^docs\(?!debug\)(?'display'.*)\.(txt|rtf)");
String[] filelist = Directory.GetFiles("docs\\", "*", SearchOption.AllDirectories);
foreach ( String file in filelist )
{
Match m = filter.Match(file);
if ( m.Success )
{
listControl.Items.Add(m.Groups["display"]);
}
}
这有点简化和巩固,实际的正则表达式是根据从文件读取的字符串创建的,我在两者之间做了更多的错误检查。)
我需要能够挑选出一个部分(通常是相对的)路径和文件名)用作显示名称,同时忽略具有特定文件夹名称作为其路径部分的任何文件。例如,对于这些文件,只有带有 + 的文件应该匹配:
+ docs\info.txt
- docs\data.dat
- docs\debug\info.txt
+ docs\world\info.txt
+ docs\world\pictures.rtf
- docs\world\debug\symbols.rtf
我的正则表达式适用于大多数文件,但我不确定如何使其在最后一个文件上失败。关于如何开展这项工作有什么建议吗?
I have a C# app that uses the search functions to find all files in a directory, then shows them in a list. I need to be able to filter the files based on extension (possible using the search function) and directory (eg, block any in the "test" or "debug" directories from showing up).
My current code is something like:
Regex filter = new Regex(@"^docs\(?!debug\)(?'display'.*)\.(txt|rtf)");
String[] filelist = Directory.GetFiles("docs\\", "*", SearchOption.AllDirectories);
foreach ( String file in filelist )
{
Match m = filter.Match(file);
if ( m.Success )
{
listControl.Items.Add(m.Groups["display"]);
}
}
(that's somewhat simplified and consolidated, the actual regex is created from a string read from a file and I do more error checking in between.)
I need to be able to pick out a section (usually a relative path and filename) to be used as the display name, while ignoring any files with a particular foldername as a section of their path. For example, for these files, only ones with +s should match:
+ docs\info.txt
- docs\data.dat
- docs\debug\info.txt
+ docs\world\info.txt
+ docs\world\pictures.rtf
- docs\world\debug\symbols.rtf
My regex works for most of those, except I'm not sure how to make it fail on the last file. Any suggestions on how to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试Directory.GetFiles。这应该做你想做的。
例子:
Try Directory.GetFiles. This should do what you want.
Example:
的字符串
docs\
开头、debug\
(\b
锚点确保我们匹配debug
作为整个单词),并.txt
或.rtf
结尾。will match a string that
docs\
,debug\
anywhere (the\b
anchor ensures that we matchdebug
as an entire word), and.txt
or.rtf
.