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 there
module 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}\b
matches 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 year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to match a URL using Python regex?
- How to replace all using Python regex?
- How to match a UUID using Python regex?
- How to split using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
See more codes...