Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用正则表达式搜索文件_C#_Regex_Search - Fatal编程技术网

C# 用正则表达式搜索文件

C# 用正则表达式搜索文件,c#,regex,search,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)) {

我有以下递归搜索功能:

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);
}

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

如果要匹配“.”,则必须将其转义为“\”其本身表示任意字符n次。请在此处查看有关格式的详细信息:

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

和方法接受非正则表达式的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个或更多字符,但不匹配换行符。

我使用了
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
}
string[]allFiles=Directory.GetFiles(@“C:\Users\UserName\Desktop\Files”);
列出所需的文件=(来自所有文件中的c)
其中Path.GetFileName(c).StartsWith(“fileStartName”)
选择c.ToList();
foreach(neededFiles中的var文件)
{
//使用匹配的文件执行所需的tesk
}

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

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

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

return Directory.EnumerateFiles(strDir, line + "*.*", SearchOption.AllDirectories)
                .Select(f => new FileInfo(f))
                .ToList();
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();
第二个是您最初寻找的,它使用实际的正则表达式执行linq查询。可以这样做:

return Directory.EnumerateFiles(strDir, line + "*.*", SearchOption.AllDirectories)
                .Select(f => new FileInfo(f))
                .ToList();
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方式”中搜索文件方法所需的签名。此外,我使用的是
SearchOption.AllDirectories
标志,它为您执行递归搜索,而无需编写自己的代码

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

  • 您正试图将正则表达式对象与字符串连接起来。这是不可能的,因为您正在查看带有字符串的正则表达式模式。这应该在构建regex对象之前(或内部)完成,如我在示例中所示

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


  • 无法将正则表达式传递给
    .GetDirectories
    。试试
    1234c.*
    (这里,
    是一个文字点,
    *
    表示任意数量的字符)。不要忘记将签名更改为
    公共列表搜索\u文件(字符串strDir,字符串line,字符串r)
    如果
    1234
    ,则
    r
    必须是
    c.
    。它对你有用吗?我不想只找到c.*文件我想找到1234[a-z].*文件。我知道了,我贴了一个答案,希望它对你有用。我想你不了解我的情况。。。文件名不仅仅是1234。。。可能是1234559993324。。。现在我想得到这个身份证的每一个版本。例如,字符串行“1111”的可能版本有以下两个:1111[a-z]。anything和1111。anything第二个版本没有问题:foreach(Directory.GetFiles(strDir,line+“*”)中的字符串strFile),但我不知道如何找到第一个版本。您无法连接字符串和正则表达式对象,这就是您所做的。对于正则表达式,可以使用
    \d+
    而不是数字。如果只需要匹配4个数字,请使用
    \d{4}
    。如果您计划允许上述两种模式,则该模式仍然相同:
    \d{4}.*
    因为
    [a-z]
    是可选的,对吗?我已更改了答案,请查看(现在,仅根据模式检查文件名。此外,如果您计划获取以数字+某物开头的文件,则需要在模式开头添加
    ^
    。如果您对需要匹配的文件的正确正则表达式有问题,请给我一条注释。您可以在上检查模式。谢谢,但我知道这一点以前的解决方案。问题是有这样的文件(如果我搜索“1234”):12344256754325.我不想得到这个文件!用你的方法我也得到这个文件…你能更清楚地知道文件名的确切模式吗?使用我上面的第二个选项对你有用,但你需要改进正则表达式以更好地匹配。