Java中的等效findAll python方法

时间:2022-05-02 22:32:25

I'm wondering if in Java there is the equivalent python method findAll. Often I read a file line by line to check if that line matches a regular expression. So if in python I can do:

我想知道在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())

is there a similar method to do this in Java?

是否有类似的方法在Java中执行此操作?

2 个解决方案

#1


1  

You can use java8 stream api.

你可以使用java8 stream 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());
}

If you don't want a try block, you can use (this will read all file lines in memory)

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

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

#2


0  

Well, there is no such a method in Java. But you can use similar code as below;

好吧,Java中没有这样的方法。但您可以使用类似的代码,如下所示;

        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("regex pattern");

        try(BufferedReader reader = new BufferedReader(new FileReader(new File("file path")))) {
            reader.lines().forEach(line -> {
                java.util.regex.Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    String gr = matcher.group(1); // Depends on the regex provided. Better if it could be grouped.
                }
            });
        }

#1


1  

You can use java8 stream api.

你可以使用java8 stream 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());
}

If you don't want a try block, you can use (this will read all file lines in memory)

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

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

#2


0  

Well, there is no such a method in Java. But you can use similar code as below;

好吧,Java中没有这样的方法。但您可以使用类似的代码,如下所示;

        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("regex pattern");

        try(BufferedReader reader = new BufferedReader(new FileReader(new File("file path")))) {
            reader.lines().forEach(line -> {
                java.util.regex.Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    String gr = matcher.group(1); // Depends on the regex provided. Better if it could be grouped.
                }
            });
        }