java - 在流上执行正则表达式

标签 java regex

我有一些大型文本文件,我将对其进行连续匹配(只是捕获,而不是替换)。我认为将整个文件保存在内存中并不是一个好主意,而是使用 Reader

我对输入的了解是,如果有匹配项,它不会超过 5 行。所以我的想法是有某种缓冲区只保留这 5 行左右,进行第一次搜索,然后继续。但它必须“知道”正则表达式匹配结束的位置才能起作用。例如,如果匹配在第 2 行结束,它应该从这里开始下一次搜索。是否有可能以高效的方式做这样的事情?

最佳答案

您可以使用ScannerfindWithinHorizon方法:

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.MULTILINEPattern.DOTALL

关于java - 在流上执行正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3013669/

相关文章:

java - 使用 Java 编程处理 Excel 表格

java - 仅当字符串包含每个列表中的单词时才匹配的正则表达式

php - 如何拆分文本以匹配双引号加上尾随文本以点?

java - 如何使用 Eclipse 捕获 Java 软件的结构

Java 64 位安装在 64 位 Windows 7 中抛出不兼容的 64 位错误

java - Spring Cloud Config 服务器显示 invalidPrivateKey

php - PHP 正则表达式和 JavaScript 正则表达式之间的区别

java - 如何从Java中的应用程序中提取所有字符串

javascript - 正则表达式获取不带括号的数字 ()

java - 谁将 JVM file.encoding 重置回原始值?