Prem
Prem

Reputation: 5997

Regular expression for durations

I am exploring regular expression and I have tried to match the following pattern using the mentioned regular expression in javascript

Pattern : 0 to 23h OR 0 to 59m

Example : Expected strings : 0h upto 23h OR 0m upto 59m

Regex : /^(([0-1]?[0-9]h|2[0-3]h)|([0-5][0-9]m))?$/.

It verifies the 0-23h successfully but fails for 0-59m. I guess something goes wrong in the way the OR operator is used between 0-23h and 0-59m

Upvotes: 0

Views: 192

Answers (2)

Allan
Allan

Reputation: 12448

what about this regex:

^(([0-1]?[0-9]h|2[0-3]h)|([0-5]?[0-9]m))?$

tested here: https://regex101.com/r/exDcKs/2

however notice that with this regex

00h or 0h
01h or 1h
02h or 2h
03h or 3h
04h or 4h
05h or 5h
06h or 6h
07h or 7h
08h or 8h
09h or 9h

are both accepted and this is the same for the minutes!!! In order to reject timestamps starting with a 0 like 01h or 01m use the following regex:

^(([0-9]h|1[0-9]h|2[0-3]h)|([0-9]m|[1-5][0-9]m))?$

https://regex101.com/r/exDcKs/3

Upvotes: 1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

As I mentioned in the comments. The reason is because your regex for minutes:

[0-5][0-9]m

Always matches two digits, so it will fail for: 0m, 1m, 2m, ... 9m. To fix that simply add a ? after [0-5] so it can be optionally ignored:

[0-5]?[0-9]m

Entire Regex:

^(([0-1]?[0-9]h|2[0-3]h)|([0-5]?[0-9]m))?$

Upvotes: 4

Related Questions