java - 许多短片或一大段文本的正则表达式更快吗?

标签 java regex

我想对文件内容执行一些正则表达式替换(在 Java 中)。

这样会不会更有效率

  1. 读取文件的一行;正则表达式替换它,将它添加到字符串文件,然后读取下一行;等

  1. 将整个文件读入字符串文件;然后用正则表达式替换那个大字符串。

是否对此进行了研究,或者有人对此有所了解吗?

我猜 #2 的性能会更高,但会使用更多内存,但我想确定一下。

最佳答案

第二种方法会更快。但请相信我的话,接受我的代码!

File f = new File("somefile.txt"); // Get the file
List<String> lines_list = Files.readAllLines(f.toPath()); // read the file
StringBuilder str = new StringBuilder(); // the file is a list, lets create a string
lines_list.forEach(str::append); // add all of the lines to the string builder
final String fileString = str.toString(); // finally create a string from it.

long startTime = System.nanoTime();
lines_list.forEach(item -> item = item.replaceAll("\\^([0-9]+)", "<sup>$1</sup>"));
long endTime = System.nanoTime();
System.out.println("Iterating and replacing over list: "+(endTime - startTime));

startTime = System.nanoTime();
fileString.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");
endTime = System.nanoTime();
System.out.println("Replacing the entire string: "+(endTime - startTime));

结果

Iterating and replacing over list: 156046464
Replacing the entire string: 1473488

请注意,我正在使用一个列表来复制您的第一个场景。我认为无论如何,您都必须将其作为列表来处理。

请注意,第二种方法在处理非常大的文件时要快 100 倍。我在文本中使用了圣经,因为它是免费的。这是 4.5 MB 的简单文本。

关于java - 许多短片或一大段文本的正则表达式更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809450/

相关文章:

javascript - 如何使用javascript从字符串中解析函数名称?

Java 模式匹配器赋值

用于调整空格的 Java 正则表达式

java - 如何在 Hadoop 中显式指定 map 节点或 reduce 节点

java - RSA key 对不起作用

python - 无法在 python 中使用 "regex"和 "re"模块进行大小写转换

javascript - JS高亮匹配内容x次

java - 在 netbeans 中调试的 Junit 测试比没有调试的情况下运行要慢得多

java - 从子类对象使用父类(super class)的 getClass 方法

Python解析表达式并替换为另一个表达式