Benjamin H
Benjamin H

Reputation: 5484

Kotlin: How to get a capture group of the first line that matches?

  1. Starting with a lineSequence
  2. I'd like to test if a Regex matches, and if so, get the first match
  3. Furthermore, I'd like to return a capturing group from that Regex match

If I didn't care, I'd do a "first" on the lineSequence, and if it existed, re-run the regex.

val possibleMatch = input.lineSequence().first { myRegex.matches(it) }

... but I want to be kotlin-cool and not have to re-run the regex. Should I use a map to a MatchGroup and filter out nulls? Feels more verbose than it could be...

input.lineSequence()
.mapNotNull { myRegex.find(it) }
.map { it.groupValues[1] }
.first()

Upvotes: 7

Views: 6852

Answers (1)

hotkey
hotkey

Reputation: 148129

You can simplify it to single .mapNotNull { ... }:

input.lineSequence()
    .mapNotNull { regex.find(it)?.groupValues?.get(1) }
    .first()

If .find(it) returns null, the value will still be dropped from the sequence, and otherwise it will be processed in the same call.

Upvotes: 10

Related Questions