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 perform a zero length match with Python Regex?
- How to remove numbers from a string using Python regex?
- How to replace a certain group using Python regex?
- How to match one or more occurence in Python regex?
- How to replace all using Python regex?
- How to match zero or one occurence in Python regex?
- How to match HTML tags with regex in Python?
- How to ignore case in Python regex?
- How to use named groups with regex in Python?
- How to match a float with regex in Python?
See more codes...