我有一些大型文本文件,我将对其进行连续匹配(只是捕获,而不是替换)。我认为将整个文件保存在内存中并不是一个好主意,而是使用 Reader
。
我对输入的了解是,如果有匹配项,它不会超过 5 行。所以我的想法是有某种缓冲区只保留这 5 行左右,进行第一次搜索,然后继续。但它必须“知道”正则表达式匹配结束的位置才能起作用。例如,如果匹配在第 2 行结束,它应该从这里开始下一次搜索。是否有可能以高效的方式做这样的事情?
最佳答案
您可以使用Scanner
和findWithinHorizon
方法:
Scanner s = new Scanner(new File("thefile"));
String nextMatch = s.findWithinHorizon(yourPattern, 0);
来自 findWithinHorizon
上的 API :
If horizon is 0, then the horizon is ignored and this method continues to search through the input looking for the specified pattern without bound. In this case it may buffer all of the input searching for the pattern.
旁注:在多行匹配时,您可能需要查看常量 Pattern.MULTILINE
和 Pattern.DOTALL
。
关于java - 在流上执行正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3013669/