Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex not working with Stream filter()

I am trying to get certain text out from a line that I get when using the new Stream in Java 8.

This is what I am reading in:

46 [core1]
56 [core1]
45 [core1]
45 [core2]
67 [core2]
54 [core2]

And here is the code I read it with currently:

Path path = Paths.get("./src/main/resources/", "data.txt");
            try(Stream<String> lines = Files.lines(path)){
                List<Integer> temps = new ArrayList<>();
                lines
                        .filter(line -> line.contains("[core1]"))
                        .filter(line -> line.contains("(\\d+).*"))
                        .flatMapToInt(temperature -> IntStream.of(Integer.parseInt(temperature)))
                        .forEach(System.out::println);
                System.out.print(temps.size());
            }

I have checked the regex expression in https://www.regex101.com/ and it seems to work fine. Also if I just search for the [core1] string, it will find it.

The problem is that when using all of this together, I get 0 matches. My logic behind this currently is that I read a line, see what core it is, and then get it's number before it. After that I want to add it to a List.

What am I doing wrong here?

like image 347
Kaspar Avatar asked Apr 22 '15 18:04

Kaspar


1 Answers

contains works only with strings (regexes not supported)... you can use line.matches("(\\d+).*") for achieving the same.

like image 65
karthik manchala Avatar answered Sep 23 '22 21:09

karthik manchala