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 year with Python Regex?
- How to replace all using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to validate an IP using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
- How to use quantifiers in Python regex?
- How to use negative lookbehind in Python regex?
- How to match HTML tags with regex in Python?
- How to regex match excluding a character in Python?
See more codes...