正则表达式搜索一个非常大的文件 [英] Regexp search through a very large file

查看:57
本文介绍了正则表达式搜索一个非常大的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用正则表达式扫描一个 300MB 的文本文件.

I need to scan a 300MB text file with a regex.

  • 读取整个文件并将其放入变量会占用超过 700MB 的 RAM,然后因无法分配内存"错误而失败.
  • 匹配可以是两行或三行,所以我不能在循环中使用逐行步进.

是否有任何懒惰的方法可以使用正则表达式进行完整文件扫描而不将其读入单独的变量?

Is there any lazy method to do a full file scan with a regex without reading it into a separate variable?

UPD

完成.现在您可以使用此功能按块读取.根据您的目标对其进行修改.

Done. Now you can use this function to read by chunks. Modify it for your goals.

def prepare_session_hash(fname, regex_string, start=0)
  @session_login_hash = {}
  File.open(fname, 'rb') { |f|
    fsize = f.size
    bsize = fsize / 8
    if start > 0
      f.seek(start)
    end

    overlap = 200

    while true
      if (f.tell() >= overlap) and (f.tell() < fsize)
        f.seek(f.tell() - overlap)
      end
      buffer = f.read(bsize)
      if buffer
        buffer.scan(s) { |match|
          @session_login_hash[match[0]] = match[1]
        }
      else
        return @session_login_hash
      end
    end
  }
end

推荐答案

  1. 以块的形式遍历文件,而不是逐行,其中块是由频繁出现的字符或模式(例如X")的出现创建的.
  2. X"是这样的,它永远不会出现在你的正则表达式中,即X"是你的正则表达式永远不会匹配字符串的地方.
  3. 在当前块中匹配您的正则表达式,提取匹配项并继续下一个块.

示例:

This is string with multline numbers -2000
2223434
34356666
444564646
. These numbers can occur at 34345
567567 places, and on 67
87878 pages . The problem is to find a good
way to extract these more than 100
0 regexes without memory hogging.

在本文中,假设所需的模式是数字字符串,例如 /d+/s 匹配数字多行,然后你可以选择一个块创建模式,而不是处理和加载整个文件,在这种情况下说 FULL STOP . 并且只读取和处理直到这个模式,然后移动到下一个块.

In this text, assume the desired pattern is numeric strings e.g /d+/s match digits multiline, Then instead of processing and loading whole file, you can chose a chunk creating pattern, say FULL STOP in this case . and only read and process till this pattern, then move to next chunk.

块#1:

This is string with multline numbers -2000
2223434
34356666
444564646
.

块#2:

These numbers can occur at 34345
567567 places, and on 67
87878 pages

等等.

从评论中添加@Ranty 的建议:

Adding @Ranty's suggestion from the comments as well:

或者简单地阅读一些行,比如 20.当你找到匹配内,清除到匹配结束并附加另外 20 行.无需计算频繁出现的X".

Or simply read by some amount of lines, say 20. When you find the match within, clear up to the match end and append another 20 lines. No need for figuring frequently occurring 'X'.

这篇关于正则表达式搜索一个非常大的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆