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
0xFFFCode explanation
- import re: imports the- remodule which contains the- re.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 the- re.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 the- regex.search()function.
- print(hex_number.group()): prints the matched hex number using the- group()method.
Helpful links
More of Python Regex
- How to match whitespace in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a plus sign in Python regex?
- How to match a question mark in Python regex?
- How to regex match excluding a word in Python?
- How to replace in a file using Python regex?
- How to ignore case in Python regex?
- How to use word boundaries in Python Regex?
- How to remove numbers from a string using Python regex?
- How to quote in Python regex?
See more codes...