使用 Java 在文件中搜索正则表达式 [英] Regex Search In Files using Java

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

问题描述

我在这里问的问题应该很常见,但我的目的是找出最好的方法.

What I ask here should be pretty common but my intent is to figure out the best possible way to do it.

  • 我有一个目录中的文件列表(比如 n) - 所有这些文件都有按扩展分类.
  • 我有一个包含正则表达式模式(比如 m)的 csv 文件,我想在所有这些特定类型的文件中查找.
  • 我想要一个最终输出,其中我有一个正则表达式模式、文件名、列出了行和行号.

以下是我应该如何解决这个问题的几个问题:

Here are the few questions I have about how I should approach this:

  1. 有没有办法避免 m*n 次操作?
  2. 什么更快 - 在搜索所有正则表达式之前读取文件,缓冲内容并将每一行存储在数组中,或者我应该采用正则表达式模式,逐行读取文件并在解析时搜索而不使用内存不足?
  3. 我认为读/写操作是最费力的 - 因此,我希望有 'n+1' 次读取(文件、csv)并且在最后只进行一次写入.我的假设和方法是否正确?
  4. 数组、列表、哈希图、其他东西 - 关于完成任务的最佳方式有什么建议吗?我认为解析文件是提高效率的关键?
  5. 我可以使用哪些特定的不常见"Java API 来显着减少代码?

感谢您对此问题的任何见解/帮助.

I appreciate any insight/help with respect to this question.

.

推荐答案

先写一个简单的工作解决方案,然后优化它.也就是说,我认为您可以执行以下操作:

Write a simple working solution first, then optimize it. That said, I think you might be able to do something like:

  • 根据您要搜索的每个单独的正则表达式构建一个复合正则表达式.如果他们不使用捕获模式,我怀疑您可以执行类似 "(regex1)|(regex2)|(regex3)" 之类的操作,这将是有效的.不过,我并不乐观——我一直不清楚正则表达式捕获组在不同的 | 分支中是如何工作的.
  • 使用 Pattern.compile(regexString) 来预编译正则表达式,这样它就不会被多次重建.
  • 使用 Guava 的 Files.toString(File, Charset) 一次性读取每个文件.如果您热衷于逐行执行,请使用 Files.readLines(File, Charset)得到一个 List.您甚至可以使用成熟的基于回调的 Files.readLines(File, Charset, LineProcessor) 来避免一次将整个文件放入内存中.
  • 使用编译后的 Pattern 来匹配目标文件——您可能需要使用 Matcher 来确定匹配的确切位置,以及哪个模式匹配.
  • Construct a composite regex from each of the individual regexes that you're searching for. If they don't use capturing patterns, I suspect you could just do something like "(regex1)|(regex2)|(regex3)" and that'd be valid. I'm not positive, though -- I've never been clear on how regex capturing groups work in when they're in different | branches.
  • Use Pattern.compile(regexString) to precompile the regex so it's not rebuilt more than once.
  • Use Guava's Files.toString(File, Charset) to just slurp each file all at once. If you're that keen on doing it line-by-line, use Files.readLines(File, Charset) to get a List<String>. You might even use the full-blown callback-based Files.readLines(File, Charset, LineProcessor) to avoid having the whole file in memory at once.
  • Use the compiled Pattern to match against the target file -- you'll probably need to use the Matcher to identify where exactly the match was, and which pattern was matched.

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

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