A UUID-4 has five groups of lowcase hexadecimal characters, the first has 8 chars, the second 4 chars, the third 4 chars, the fourth 4 chars, the fifth 12 chars.
However to make it a valid UUID4 the third group (the one in the middle) must start with a 4:
00000000-0000-4000-0000-000000000000
^
And the fourth group must start with 8, 9, a or b.
00000000-0000-4000-a000-000000000000
^ ^
The regex:
[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}
The regex, but -
is optional
[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}
The regex to use as django slug
(?P<slug>[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})
The regex with uppercase support
[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}
The regex with uppercase support, but -
is optional
[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?4[0-9a-fA-F]{3}-?[89abAB][0-9a-fA-F]{3}-?[0-9a-fA-F]{12}
The regex with uppercase support to use as django slug
(?P<slug>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})
The regex with uppercase support to use as django slug, but -
is optional
(?P<slug>[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?4[0-9a-fA-F]{3}-?[89abAB][0-9a-fA-F]{3}-?[0-9a-fA-F]{12})
@sometimescasey if your plan is to use with Django url, consider using the built-in
uuid
Path converter https://docs.djangoproject.com/en/3.1/topics/http/urls/#path-convertersWhen I created this gist, Path converters did not yet exist in Django and it was added only in Django 2.0.
Edit:
Okay. Django's UUID regex is generic and captures uuid in other formats not compatible with uuid4 :-|
https://github.com/django/django/blob/3.1.7/django/urls/converters.py#L26 .