How to match values into separate optional groups with a regex based on character?

3 examples of input:

"13-4h50m2s"
"13-4h2s"
"13-50m"

Preferred code:

const [hours = 0, minutes = 0, seconds = 0] = input.match(some_regexp)

Wanted output {hours,minutes,seconds} for the 3 examples:

{hours: 4, minutes: 50, seconds: 2}
{hours: 4, minutes: 0,  seconds: 2}
{hours: 0, minutes: 50, seconds: 0}

Regex I’ve tried: /(\d+)?[a-z](\d+)?[a-z]?(\d+)?[a-z]?/. But then the second example doesn’t work.

EDIT

Actually, input can be expected to be sorted in the right order (h,m,s).
And it doesn’t matter if the values are stored as strings or numbers.

7 thoughts on “How to match values into separate optional groups with a regex based on character?”

Leave a Comment