CodeRonin
CodeRonin

Reputation: 2109

equivalent findAll python method in Java

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:

 # 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?

Upvotes: 1

Views: 2256

Answers (2)

Sachith Dickwella
Sachith Dickwella

Reputation: 1490

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

        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.
                }
            });
        }

Upvotes: 1

zhh
zhh

Reputation: 2406

You can use 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)

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

Upvotes: 5

Related Questions