phoney_badger
phoney_badger

Reputation: 523

hours:minutes:seconds Timestamp regex

I'm trying to validate a user inputed video timestamp in the format hours:minutes:seconds using a regex. So I'm assuming the hours component can be arbitrarily long, so the final format is basically hhhh:mm:ss where there can be any number of h. This is what I have so far

(([0-9]+:)?([0-5][0-9]:))?([0-5][0-9])

where

(
  ([0-9]+:)?    # hh: optionally with an arbitrary number of h
  ([0-5][0-9]:) # mm: , with mm from 00 to 59
)?              # hh:mm optionally
([0-5][0-9])    # ss , wtih ss from 00 to 59

which I believe is almost there, but doesn't handle cases like 1:31 or just 1. So to account for this if I add the first digit inside the mm and ss blocks as optional,

(([0-9]+:)?([0-5]?[0-9]:))?([0-5]?[0-9])

firstly the last seconds block starts matching values like 111. Also values like 1:1:12 are matched , which I don't want (should be 1:01:12). So how can I modify this so that m:ss and s are valid whereas h:m:ss,m:s and sss are not?

I am new to regular expressions, so apologies in advance if I'm doing something stupid. Any help is appreciated. Thanks.

Upvotes: 1

Views: 2252

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

You can match either 1 or more digits followed by an optional :mm:ss part, or match mm:ss.

To also match 6:12 and not 1:1:12 make only the first digit optional in the second part of the pattern.

^(?:\d+(?::[0-5][0-9]:[0-5][0-9])?|[0-5]?[0-9]:[0-5][0-9])$
  • ^ Start of string
  • (?: Non capture group
    • \d+ Match 1+ digits
    • (?::[0-5][0-9]:[0-5][0-9])? Match an optional :mm:ss part, both in range 00 - 59
    • | Or
    • [0-5]?[0-9]:[0-5][0-9] Match m:ss or mm:ss both in range 00-59 where the first m is optional
  • ) Close non capture group
  • $ End of string

Regex demo

Upvotes: 1

anotherGatsby
anotherGatsby

Reputation: 1598

Doesn't adding the positional anchors(^ and $)solve your problem?

^(([0-9]+:)?([0-5][0-9]:))?([0-5][0-9])$

Check here: https://regex101.com/r/fRZf2R/1

Upvotes: 1

Related Questions