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 theremodule 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.Iflag 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 replace all using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to replace in a file using Python regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match a plus sign in Python regex?
- How to get the href attribute value from a regex in Python?
- How to validate an IP using Python regex?
- How to quote in Python regex?
- How to use word boundaries in Python Regex?
See more codes...