Matcher.results()
Returns all matches at once as a stream — a short replacement for a find() loop.
Available since: Java 9
Syntax
public Stream<MatchResult> results()Return value
Stream<MatchResult>A stream of MatchResult objects with group(), start(), end().
Examples
Every hashtag in a text, collected into a list:
void main() {
String post = "Learning #java and #regex today #java";
List<String> tags = Pattern.compile("#(\\w+)").matcher(post)
.results()
.map(r -> r.group(1))
.distinct()
.toList();
IO.println(tags);
}Output:
[java, regex]Notes
The stream is lazy and uses the Matcher state, so it cannot be traversed twice. To count matches, results().count() is handy.
See also
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- Matcher.group() — Returns the text of the current match or of one of its parenthesized groups.
- Pattern.matcher() — Creates a Matcher that searches for the pattern in a specific string.
In the tutorial
- Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.