Is there an existing way of getting regex capture ...
# getting-started
z
Is there an existing way of getting regex capture group value by delegate? Maybe it falls under the realm of easy-enough-to-wing-it, or why-would-you-need-it, but something like this in stdlib
Copy code
operator fun MatchResult.getValue(parent: Nothing?, property: KProperty<*>): String =
    groups[property.name]?.value ?: ""
I wanted a nicer way to deal with missing values during serialization, so ended up using this for my deserialization, but I'd love to know what the caveats are
Copy code
@Serializable(with = PidSerializer::class)
data class Pid(
    val first: Digits,
    val second: Digits? = null,
)
...
    override fun deserialize(decoder: Decoder): Pid =
        decoder.decodeString().toOption()
            .flatMap { pidPattern.matchEntire(it).toOption() }
            .map {
                val first by it
                val second by it
                Pid(first, second.ifBlank { null })
            }.getOrNull() ?: throw MissingFieldException("first", "PID")