Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get regex matching groups using patter.asPredicate?

Suppose that I have a list:

        List<String> dest = Arrays.asList(
                  "abc abd 2000",
                  "idf owe 1200",
                  "jks ldg 789",
                  "ccc hhh 2000",
                  "www uuu 1000"
                );

and I’m trying to get the number at the end of every string. The given list has only integers in it, but I’m writing the regex for doubles too:(\\d+\\.?\\d+). In Java 1.8, I wrote the following code:

        ArrayList<String> mylist = new ArrayList<>(
                dest.stream()
                .filter(Pattern.compile("\\D+\\s\\D+\\s(\\d+\\.?\\d+)").asPredicate())
                .collect(Collectors.toList())
                );

What I’m trying to do is – get the (\\d+\\.?\\d+) group from each found string, how can I do it? I was thinking about applying a Matcher to each element of the list but I’m not sure about how to implement it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

filter keeps or removes elements from the list. If you want to transform stream elements (which you do when you extract the number), use map.

Then you can use the regex (along with a Matcher) to extract data:

Pattern p = Pattern.compile("\\D+\\s\\D+\\s(\\d+\\.?\\d+)");
List<String> mylist = dest.stream()
        .map(s -> {
          Matcher matcher = p.matcher(s);
          matcher.find();
          return matcher.group(1); //error handling sold seperately
        })
        .collect(Collectors.toList());
System.out.println(mylist);

prints

[2000, 1200, 789, 2000, 1000]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading