As of this version, you can use a new method Matcher::results
with no args that is able to comfortably return Stream<MatchResult>
where MatchResult
represents the result of a match operation and offers to read matched groups and more (this class is known since Java 1.5).
String string = "Some string with 'the data I want' inside and 'another data I want'.";
Pattern pattern = Pattern.compile("'(.*?)'");
pattern.matcher(string)
.results() // Stream<MatchResult>
.map(mr -> mr.group(1)) // Stream<String> - the 1st group of each result
.forEach(System.out::println); // print them out (or process in other way...)
The code snippet above results in:
the data I want another data I want
The biggest advantage is in the ease of usage when one or more results is available compared to the procedural if (matcher.find())
and while (matcher.find())
checks and processing.