Search code examples
javaregexstringjava-streamregex-group

Obtain Regex matching Groups using Pattern.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.


Solution

  • I'm trying to get the number at the end of every string...

    Solution 1

    Maybe you can solve it without using regex, like so:

    List<String> response = dest.stream()
            .map(String::trim)
            .map(s -> s.split("\\s+"))
            .map(r -> r[r.length - 1])
            .toList();
    

    Solution 2

    If you insist on using regex, you can use:

    final String regex = "\\D+\\s\\D+\\s(\\d+\\.?\\d+)";
    final Pattern compile = Pattern.compile(regex);
    List<String> response = dest.stream()
            .map(compile::matcher)
            .filter(Matcher::find)
            .map(r -> r.group(1))
            .toList();
    

    Outputs

    [2000.55, 1200, 789, 2000, 1000]