Java 中等效的 findAll python 方法

GJC*_*ode 1 python java methods findall equivalent

我想知道在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())
Run Code Online (Sandbox Code Playgroud)

Java中有类似的方法可以做到这一点吗?

zhh*_*zhh 5

您可以使用 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());
}
Run Code Online (Sandbox Code Playgroud)

如果你不需要 try 块,你可以使用(这将读取内存中的所有文件行)

List<String> strings = Files
    .readAllLines(Paths.get("/path/to/file"))
    .stream()
    .filter(line -> line.matches("some pattern"))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)