c# - 有没有一种使用正则表达式解析大文件的快速方法?

标签 c# regex algorithm

问题: 非常非常大的文件,我需要逐行解析以从每行中获取 3 个值。一切正常,但解析整个文件需要很长时间。有可能在几秒钟内完成吗?通常需要 1 到 2 分钟。

示例文件大小为 148,208KB

我正在使用正则表达式来解析每一行:

这是我的 C# 代码:

private static void ReadTheLines(int max, Responder rp, string inputFile)
{
    List<int> rate = new List<int>();
    double counter = 1;
    try
    {
        using (var sr = new StreamReader(inputFile, Encoding.UTF8, true, 1024))
        {
            string line;
            Console.WriteLine("Reading....");
            while ((line = sr.ReadLine()) != null)
            {
                if (counter <= max)
                {
                    counter++;
                    rate = rp.GetRateLine(line);
                }
                else if (max == 0)
                {
                    counter++;
                    rate = rp.GetRateLine(line);
                }
            }
            rp.GetRate(rate);
            Console.ReadLine();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

这是我的正则表达式:

public List<int> GetRateLine(string justALine)
{
    const string reg = @"^\d{1,}.+\[(.*)\s[\-]\d{1,}].+GET.*HTTP.*\d{3}[\s](\d{1,})[\s](\d{1,})$";
    Match match = Regex.Match(justALine, reg,
                                RegexOptions.IgnoreCase);

    // Here we check the Match instance.
    if (match.Success)
    {
        // Finally, we get the Group value and display it.

        string theRate = match.Groups[3].Value;
        Ratestorage.Add(Convert.ToInt32(theRate));
    }
    else
    {
        Ratestorage.Add(0);
    }
    return Ratestorage;
}

这是要解析的示例行,通常大约 200,000 行:

10.10.10.10 - - [27/Nov/2002:16:46:20 -0500] "GET /solr/ HTTP/1.1" 200 4926 789

最佳答案

Memory Mapped FilesTask Parallel Library寻求帮助。

  1. 创建具有多个随机访问 View 的持久化 MMF。每个 View 对应于文件的特定部分
  2. 使用IEnumerable<string> 等参数定义解析方法, 基本上是抽象一组未解析的行
  3. 为每个 MMF View 创建并启动一个 TPL 任务 Parse(IEnumerable<string>)作为任务操作
  4. 每个工作任务都将解析后的数据添加到 BlockingCollection 的共享队列中类型
  5. 另一个 Task 监听 BC ( GetConsumingEnumerable() ) 并处理所有已被 worker Tasks 解析的数据

参见 Pipelines pattern在 MSDN 上

必须说此解决方案适用于 .NET Framework >=4

关于c# - 有没有一种使用正则表达式解析大文件的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13810693/

相关文章:

c# - c# 中 asp.net 代码隐藏的变量作用域(希望是简单的!)

javascript - 忽略 Javascript 正则表达式中的换行符

arrays - 给定两个数组 A 和 B ,找到两个数组中的第一个数字,使得替换它们使得数组 A 的总和等于数组 B 的总和

c++ - UTF-8 字符串的简单加密,结果是 NULL 终止字符串?

java - 算法,大 O 表示法 : Is this function O(n^2) ? 还是 O(n)?

c# - 为什么这个小程序给出 "Common Language Runtime detected an invalid program"?

C#:指向空数组的不安全指针为空?

c# - 使用 JSON 序列化/反序列化 TimeSpan

java - 除特定情况外如何匹配单个字符

ruby - Ruby 和 Perl 中的 Regex 语法有什么区别?