Skip to content

Instantly share code, notes, and snippets.

@luzfcb
Last active September 20, 2024 13:28
Show Gist options
  • Save luzfcb/186ee28b368450035e056228615db999 to your computer and use it in GitHub Desktop.
Save luzfcb/186ee28b368450035e056228615db999 to your computer and use it in GitHub Desktop.
uuid4 python regex . django slug

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

@luzfcb regardless, good to know! Thanks for the details 👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment