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

3 examples of input:


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.


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.

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

  1. Link exchange is nothing else except it is just placing the other person’s
    blog link on your page at appropriate place and other person will also do same in support of you.

  2. Excellent goods from you, man. I’ve understand your
    stuff previous to and you’re just extremely great. I really like
    what you’ve acquired here, certainly like what you’re stating and the way in which you
    say it. You make it entertaining and you still take care of to keep it sensible.

    I can not wait to read far more from you. This is really a wonderful website.

    Have a look at my homepage: poker pulsa online

  3. Useful information. Fortunate me I found your
    web site by chance, and I’m stunned why this coincidence did not came about earlier!
    I bookmarked it.

  4. When someone writes an paragraph he/she retains the image of a user in his/her brain that how a user can understand it.
    Therefore that’s why this piece of writing is perfect.

  5. Awesome blog! Is your theme custom made or did you download it
    from somewhere? A design like yours with
    a few simple tweeks would really make my blog stand out. Please let me know where
    you got your theme. Many thanks

  6. 222006 694723Hi, you used to write exceptional articles, but the last several posts have been kinda boring I miss your tremendous posts. Past couple of posts are just just a little out of track! 575044


Leave a Comment