Skip to content
shellhacks.dev
Regular Expressions

Match a time of day

Match a 24 hour time of day with ([01][0-9]|2[0-3]):[0-5][0-9]. A single digit hour needs a separate alternative, and 24:00 is rejected on purpose.

1 min read
Summarize in AI

A field takes a time like 09:30 or 23:59, and a plain digits pattern would also accept 99:99.

Python
import re

rx = re.compile(r"([01][0-9]|2[0-3]):[0-5][0-9]")
for s in ["00:00", "09:30", "23:59", "24:00", "12:60", "9:30", "7:05"]:
    print(f"{s:6} {bool(rx.fullmatch(s))}")

relaxed = re.compile(r"([01]?[0-9]|2[0-3]):[0-5][0-9]")
print(bool(relaxed.fullmatch("9:30")), bool(relaxed.fullmatch("24:00")))
Text
00:00  True
09:30  True
23:59  True
24:00  False
12:60  False
9:30   False
7:05   False
True False

The hour is either a 0 or 1 followed by any digit, giving 00 to 19, or a 2 followed by 0 to 3. The minute is a digit from 0 to 5 and any digit. The Python re documentation lists the syntax used. The first loop shows that 24:00 and 12:60 fail. The relaxed variant makes the first digit optional with ?, so 9:30 is accepted.

ISO 8601 allows 24:00 as the end of a day and a leap second as 23:59:60, and this pattern rejects both. Time zones, seconds and a 12 hour clock with AM or PM each need their own additions. If you only want valid times, parsing with datetime.strptime also checks the combination for you.

Share

More snippets

Regular Expressions

Match a quoted string

Match a quoted string with a negated character class. An escaped quote inside the text ends the match early, and a PCRE alternation that pairs backslashes handles it.

1 min read
Regular Expressions

Match a semantic version

Match a semantic version with the pattern from semver.org, which runs in grep -E. It rejects leading zeros, a bare 1.2 and a v prefix, and takes pre-release tags.

1 min read
Regular Expressions

Match a UUID

Match a version 4 UUID with 8-4-4-4-12 hex groups, a 4 at the start of the third group and 8, 9, a or b at the start of the fourth. Add -i for uppercase.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.