Reputation: 5484
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
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