Using Java 11 I wonder how I can use the Stream API to extract all the group matches to a list of strings in a one-liner.
Given this regexp and string:
String regexp = "(\\d\\d\\d)-(\\d)-(\\d\\d)";
String str = "123-8-90";
I know how to obtain the result in multiple lines:
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(str);
List<String> matches = new ArrayList<>();
if (matcher.find()) {
matches.add(matcher.group(1));
matches.add(matcher.group(2));
matches.add(matcher.group(3));
}
System.out.println(matches);
This prints the expected list of 3 distinct numeric strings: [123, 8, 90]
My attempt to achieve the same in one liner:
List<String> matches = Pattern.compile(regexp)
.matcher(str)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
System.out.println(matches);
This prints the unexpected: [123-8-90]
How can I use the MatchResult::group(int) method in the stream?