使用正则表达式搜索文件

时间:2015-08-11 13:07:44

标签: c# regex search

我有以下递归搜索功能:

public List<FileInfo> Search_Files(String strDir, String line)
{
    List<FileInfo> files = new List<FileInfo>();

    try
    {
         foreach (String strFile in Directory.GetFiles(strDir,line+r))
         {
             files.Add(new FileInfo(strFile));
         }

         foreach (String strSubDir in Directory.GetDirectories(strDir))
         {
             List<FileInfo> sublist = Search_Files(strSubDir, line);

             foreach (FileInfo file_infow in sublist)
             {
                 files.Add(file_infow);
             }
         }
    }
    catch (Exception)
    {
         ...
    }

    return (files);
}

行变量的值看起来像“1234”。 现在我想搜索如下文件:1234c.something或1234.something

我创建了以下Regex:

Regex r = new Regex("[a-z].* | .*");

我将它添加到行字符串中,但它不起作用。为什么这不起作用,我该如何纠正?

4 个答案:

答案 0 :(得分:1)

我使用LINQ,试一试

string[] allFiles =  Directory.GetFiles(@"C:\Users\UserName\Desktop\Files");
List<string> neededFiles = (from c in allFiles
                               where Path.GetFileName(c).StartsWith("fileStartName")
                               select c).ToList<string>();

foreach (var file in neededFiles)
{
   // do the tesk you want with the matching files
}

答案 1 :(得分:0)

如果你想匹配&#39;。&#39;你必须逃避它,因为&#39; \。&#39;。 &#39; *&#39;本身意味着任何字符n次。请查看有关格式的详细信息:https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

我还建议您使用更严格的正则表达式。如果您知道文件名以1234开头,请在正则表达式中使用它。

答案 2 :(得分:0)

GetDirectoriesGetFiles方法接受不是正则表达式的 searchPattern

  

要匹配路径中文件名称的搜索字符串。此参数可以包含有效文字路径和通配符(*?)字符的组合(请参阅备注),但不支持正则表达式。

您可以使用以下正则表达式过滤结果:

var r = new Regex(@"\d{4}.*");
// var r = new Regex(@"^\d{4}.*"); // Use this if file names should start with the 4 digits.
files.Add(Directory.GetFiles(strDir)
            .Where(p => r.IsMatch(Path.GetFileName(p)))
            .ToList());

\d{4}.*正则表达式匹配4位数字(\d{4})和任意0个或更多字符,但换行符。

答案 3 :(得分:0)

有两种方法可以做到这一点。第一种是使用Windows搜索过滤器。这是您可以直接传递给GetFiles()方法的内容。 (EnumerateFiles()做同样的事情,在这种情况下可能会更快,但这与你的问题无关。)

Windows搜索模式使用*来表示“任意数量的任何字符”,?用于表示单个未知字符。这些实际上不是正则表达式。

然后您可以执行以下搜索:

return Directory.EnumerateFiles(strDir, line + "*.*", SearchOption.AllDirectories)
                .Select(f => new FileInfo(f))
                .ToList();

第二个是您最初寻找的并且正在使用实际正则表达式执行linq查询。这可以这样做:

Regex pattern = new Regex(line + @".*\..*") 
// regex says use line, then anything any number of times, 
// and then a dot and then any chars any amount of times

return Directory.EnumerateFiles(strDir, *.*, SearchOption.AllDirectories)
                .Where(f => pattern.IsMatch(f))
                .Select(f => new FileInfo(f))
                .ToList();

注意:以上两个示例显示了如何将提供的字符串转换为FileInfo对象,例如“linq-way”中Search_Files方法所需的签名。此外,我正在使用SearchOption.AllDirectories标志为您执行递归搜索,而无需您自己编写。

至于为什么你原来发布的方法不起作用;它有两个问题。

  1. 您正在尝试将正则表达式对象与字符串连接起来。这是不可能的,因为您希望使用字符串连接正则表达式模式。这应该在正则表达式对象的构造之前(或之内)完成,正如我在我的例子中所示。

  2. 假设您没有尝试使用字符串连接正则表达式对象,那么您使用的正则表达式模式将始终匹配任何内容。这不会限制任何事情。

相关问题