```kotlin private val DURATION = Regex("""(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?""") fun parseDuration(s: String): Long { require(s.isNotEmpty()) { "Empty duration" } val match = DURATION.matchEntire(s) ?: throw IllegalArgumentException("Invalid duration: \"$s\"") val (h, m, sec) = match.destructured // "" when a part is absent try { val hours = if (h.isEmpty()) 0L else h.toLong() val minutes = if (m.isEmpty()) 0L else m.toLong() val seconds = if (sec.isEmpty()) 0L else sec.toLong() return Math.addExact( Math.addExact(Math.multiplyExact(hours, 3600L), Math.multiplyExact(minutes, 60L)), seconds ) } catch (e: ArithmeticException) { throw IllegalArgumentException("Duration too large: \"$s\"", e) } } ``` Notes: - `matchEntire` makes the whole string match. Spaces, unknown letters, wrong order, repeated unit, and a number without a unit all fail the match. - The regex can match an empty string, so `require(s.isNotEmpty())` rejects it first. - Overflow throws `IllegalArgumentException`. `toLong()` throws `NumberFormatException`, which is already a subclass of it, and `ArithmeticException` from the `*Exact` calls is rethrown as one.