c#如何编写正则表达式过滤器

时间:2016-04-07 08:37:50

标签: c# .net regex

我正在尝试使用C#过滤目录中的文件。

我认为正则表达式是最好的方式,但我在编写表达方式时遇到麻烦...有人可以帮助我...

这是我的代码:

Regex reg = new Regex(Expr);
var files = Directory.GetFiles(Dir, "*.txt")
               .Where(path => reg.IsMatch(path))
               .ToList();

My Expression Expr会匹配所有以“fileXXX”开头并且不以“_L.txt”结尾的文件,我该如何解决我的问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

If the fileXXX is a literal, you can achieve what you need with a mere StartsWith and EndsWith:

var files = Directory
   .EnumerateFiles(Dir, "*.txt")
   .Where(path => Path.GetFileNameWithoutExtension(path).StartsWith("fileXXX") 
               && !Path.GetFileNameWithoutExtension(path).EndsWith("_L"))
   .ToList();

Note that your path contains the file path including the folder path, not just the file name. That is why you need to use Path.GetFileNameWithoutExtension(path) to perform the check on.

Else, use a regex like

var files1 = Directory
   .GetFiles(Dir, "*.txt")
   .Where(path => Regex.IsMatch(Path.GetFileNameWithoutExtension(path), @"^fileXXX.*(?<!_L)$"))
   .ToList();

Where ^fileXXX.*(?<!_L)$ matches any text (here, a file name without extension) that starts with fileXXX and does not end with _L (due to the negative lookbehind (?<!_L) before an end of string anchor $).