python-regexHow to match a hex number with regex in Python?
Regex can be used to match a hex number in Python using the \b metacharacter. This metacharacter matches the beginning or end of a word. The following example code will match a hex number with up to 8 digits:
import re
hex_regex = re.compile(r'\b[0-9A-F]{1,8}\b')
hex_number = hex_regex.search('The hex number is 0xFFF')
print(hex_number.group())
Output example
0xFFF
Code explanation
import re: imports theremodule which contains there.compile()function used to create a regex object.hex_regex = re.compile(r'\b[0-9A-F]{1,8}\b'): creates a regex object using there.compile()function. The regex pattern\b[0-9A-F]{1,8}\bmatches a hex number with up to 8 digits.hex_number = hex_regex.search('The hex number is 0xFFF'): searches for a hex number in the given string using theregex.search()function.print(hex_number.group()): prints the matched hex number using thegroup()method.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to perform a zero length match with Python Regex?
- How to match whitespace in Python regex?
- How to ignore case in Python regex?
- How to get all matches from a regex in Python?
- How to make a case insensitive match with Python regex?
- How to match a URL path using Python regex?
- How to get a group from a regex in Python?
- How to match a plus sign in Python regex?
See more codes...