-
-
Save wellic/412769b07da2fb2c46f45d1e204d1d67 to your computer and use it in GitHub Desktop.
UUID regular expressions (regex) with usage examples in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment