Skip to content
Advertisement

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()
    foo(m.group(x));
} 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))
    .orElse(...);

and also a stream of match results like:

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

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

Advertisement

Answer

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

p.matcher(input)
 .results()
 .map(MatchResult::group)
 .findAny()
 .orElse(null);

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement