python-regexHow to match a UUID using Python regex?
Python regex can be used to match a UUID using the re
module. The following example code will match a UUID:
import re
pattern = re.compile(r'[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
match = pattern.match('12345678-1234-4abc-8bcd-123456789abc')
if match:
print('UUID matched!')
Output example
UUID matched!
The code consists of the following parts:
import re
: imports there
module which provides regular expression matching operations.pattern = re.compile(r'[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
: compiles the regular expression pattern which matches a UUID. The pattern consists of 8 hexadecimal digits, followed by an optional hyphen, followed by 4 hexadecimal digits, followed by an optional hyphen, followed by 4 hexadecimal digits, followed by an optional hyphen, followed by 3 hexadecimal digits, followed by an optional hyphen, followed by 12 hexadecimal digits. There.I
flag makes the pattern case-insensitive.match = pattern.match('12345678-1234-4abc-8bcd-123456789abc')
: attempts to match the pattern against the given string.if match:
: checks if the pattern matched the given string.print('UUID matched!')
: prints a message if the pattern matched the given string.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match the beginning of a line with Python regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to replace all using Python regex?
- How to ignore case in Python regex?
- How to get a group from a regex in Python?
- How to match whitespace in Python regex?
See more codes...