Skip to content
shellhacks.dev
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
Summarize in AI

An ID in a log or a request has to be a UUID, and eight hex digits followed by dashes in the right places is not the whole rule.

Shell
re='^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
for u in 123e4567-e89b-42d3-a456-426614174000 123E4567-E89B-42D3-A456-426614174000 123e4567-e89b-12d3-a456-426614174000 00000000-0000-0000-0000-000000000000 123e4567e89b42d3a456426614174000; do
  printf '%s\n' "$u" | grep -qE "$re" && echo "match  $u" || echo "no     $u"
done
printf '%s\n' 123E4567-E89B-42D3-A456-426614174000 | grep -qiE "$re" && echo "with -i: match"
Text
match  123e4567-e89b-42d3-a456-426614174000
no     123E4567-E89B-42D3-A456-426614174000
no     123e4567-e89b-12d3-a456-426614174000
no     00000000-0000-0000-0000-000000000000
no     123e4567e89b42d3a456426614174000
with -i: match

A UUID is 32 hex digits in groups of 8, 4, 4, 4 and 12. In version 4 the first digit of the third group is the version number, a 4, and the first digit of the fourth group holds the variant bits, which for the standard variant are 8, 9, a or b, as laid out in RFC 9562. The second value fails only because it is uppercase and the third because it is version 1. The all-zero nil UUID fails as well, since it has no version.

Drop the 4 and the [89ab] to accept any version, or use [1-8] for the versions in RFC 9562. The text form is case-insensitive, so lowercase before storing it. A pattern cannot tell a random UUID from an invented one, and a database column of type uuid or a parser in your language validates the same thing with less risk.

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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.