Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active September 28, 2023 19:03
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kgriffs/c20084db6686fee2b363fdc1a8998792 to your computer and use it in GitHub Desktop.
Save kgriffs/c20084db6686fee2b363fdc1a8998792 to your computer and use it in GitHub Desktop.
UUID regular expressions (regex) with usage examples in Python
import re
# RFC 4122 states that the characters should be output as lowercase, but
# that input is case-insensitive. When validating input strings,
# include re.I or re.IGNORECASE per below:
def _create_pattern(version):
return re.compile(
(
'[a-f0-9]{8}-' +
'[a-f0-9]{4}-' +
version + '[a-f0-9]{3}-' +
'[89ab][a-f0-9]{3}-' +
'[a-f0-9]{12}$'
),
re.IGNORECASE
)
# -----------------------------------------------------------------------------
# Patterns
# -----------------------------------------------------------------------------
UUID_ALL_PATTERN = _create_pattern('[1-5]')
UUID_V4_PATTERN = _create_pattern('4')
# v1 with a randomized multicast MAC is a reasonable alternative to v4
# that is more optimal for DB indexing.
#
# UUID_V1_PATTERN = _create_pattern('1')
# UUID_V1_4_PATTERN = _create_pattern('[14]')
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
assert UUID_ALL_PATTERN.match('18a3315c-5bd2-4009-bd35-71a054e8e097')
assert UUID_ALL_PATTERN.match('6df0d487-4541-11e6-b618-28cfe914732d')
assert UUID_ALL_PATTERN.match('6DF0D487-4541-11E6-B618-28CFE914732D')
assert not UUID_ALL_PATTERN.match('18a3315c-5bd2-4009-0d35-71a054e8e097')
assert not UUID_ALL_PATTERN.match('6df0d487-4541-01e6-b618-28cfe914732d')
assert UUID_V4_PATTERN.match('18a3315c-5bd2-4009-bd35-71a054e8e097')
assert not UUID_V4_PATTERN.match('6df0d487-4541-11e6-b618-28cfe914732d')
assert UUID_V4_INPUT_PATTERN.match('18A3315C-5BD2-4009-BD35-71A054E8E097')
@vamotest
Copy link

Thank you very much! I was looking for examples on the Internet and your code helped me.

@kgriffs
Copy link
Author

kgriffs commented Nov 24, 2020

Happy to help!

@Graham-Stein
Copy link

Thank you for this. Very helpful.

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