Skip to content
shellhacks.dev
Regular Expressions

Match an ISO date

Match an ISO date with [0-9]{4}-[0-9]{2}-[0-9]{2}. The pattern checks the shape only, and a tighter month and day range still accepts February 31.

2 min read
Summarize in AI

A pattern for 2026-03-14 is easy to write, and it also approves dates that do not exist.

Shell
printf '%s\n' 2026-03-14 2026-13-45 2026-02-31 | grep -E '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
echo ---
printf '%s\n' 2026-03-14 2026-13-45 2026-02-31 | grep -E '^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$'
echo ---
for d in 2026-03-14 2026-13-45 2026-02-31; do
  date -d "$d" +%F > /dev/null 2>&1 && echo "$d valid" || echo "$d invalid"
done
Text
2026-03-14
2026-13-45
2026-02-31
---
2026-03-14
2026-02-31
---
2026-03-14 valid
2026-13-45 invalid
2026-02-31 invalid

A regular expression describes the shape of a string, and the shape of 2026-13-45 is the same as the shape of a date. Limiting the month to 01 to 12 and the day to 01 to 31 removes the impossible ones, but 2026-02-31 still passes because the pattern knows nothing about February. Calendar rules need a date library or a tool that knows them, such as GNU date -d in the last block. The format itself is defined in RFC 3339.

Use the regular expression to pick dates out of text, then validate the survivors with a parser. Add word boundary anchors, or the line anchors, so a longer number does not match inside. A time zone suffix and a time part are separate pieces of the grammar, and date -d is GNU only; BSD uses date -j -f.

Taggedregextext
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.