Functional style java.util.regex match/group extraction

The following is only available from java-9

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


There is an elegant solution that works for both Stream<String> and Optional<String>:

    Pattern pattern = Pattern.compile("...");

    List<String> input = new ArrayList<>();

    List<String> matches = input.stream()
            .map(pattern::matcher)
            .filter(Matcher::find)
            .map(m -> m.group(x))
            .collect(Collectors.toList());

Though I would like to point out that doing a modifying/mutating operation in a filter-call is unusual. Please be careful when you do mutating operations in filtercalls and avoid them as much as possible. For this case it's fine though (from my subjective viewpoint) as you modify an object you just created in your stream that isn't used outside of the stream operations.

Use Optional.ofNullable/of when you only have one input, everything else looks the same.

Tags:

Java

Regex

Java 9