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.