Skip to content

Functional style java.util.regex match/group extraction

Using java.util.regex to extract substrings I find myself implementing the same code pattern working around calls to :

Pattern p = Pattern.compile(pattern); // can be static final
Matcher m = p.matcher(input);
if (m.find()) { // or m.matches()
} else {

Is there a functional extension or popular library (guava / apache commons) that avoids the ugly unnecessary and error-prone local variable, like:

Pattern p = Pattern.compile(pattern); // can be static final
p.matchedGroup(input, x) // return Optional<String>
    .map(group -> foo(group))

and also a stream of match results like:

Pattern p = Pattern.compile(pattern);
    .map((MatchResult mr) -> {
        mr.groupsIfPresent(x).map(g -> foo(g)).orElse(...)

It seems the only functional addition in Java8 was .splitAsStream() but that only helps when trying to split around matches.



The following is only available from

You’re probably looking for Matcher::results which produces a Stream<MatchResult>

You can use it in the following way for example


An addition added by Holger and which is intersting would be, while reading a File and looking for a pattern to directly use Scanner::findAll to avoid loading the whole file in memory using File::lines