我想知道 Java 中是否有等效的 python 方法 findAll。我经常逐行读取文件来检查该行是否与正则表达式匹配。所以如果在 python 中我可以这样做:
# Feed the file text into findall(); it returns a list of all the found strings
strings = re.findall(r'some pattern', f.read())
Java中有类似的方法吗?
最佳答案
您可以使用java8流API。
List<String> strings = null;
try(Stream<String> lines = Files.lines(Paths.get("/path/to/file"))) {
strings = lines
.filter(line -> line.matches("some pattern"))
.collect(Collectors.toList());
}
如果你不需要 try block ,你可以使用(这将读取内存中的所有文件行)
List<String> strings = Files
.readAllLines(Paths.get("/path/to/file"))
.stream()
.filter(line -> line.matches("some pattern"))
.collect(Collectors.toList());
关于java - Java 中等效的 findAll python 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610511/