Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: regular expression search pattern for binary files (half a byte)

I am using the following regular expression pattern for searching 0xDEAD4FAD in a binary file:

my_pattern = re.compile(b"\xDE\xAD\x4F\xAD")

but how do I generalize the search pattern for searching 0xDEAD4xxx? can't seem to cut through half a byte

like image 707
bFig8 Avatar asked Dec 03 '13 06:12

bFig8


1 Answers

Regular expressions do allow searching over ranges. Thus, to find a byte whose the first nibble is "4" use:

pattern = re.compile(b"[\x40-\x4F]")

The following test shows that it produces the desired output:

>>> for byte in ('\x3f', '\x40', '\x42', '\x4f', '\x50'): print bool(pattern.search(byte))
... 
False
True
True
True
False

To answer your specific question about searching for 0xDEAD4xxx, use:

my_pattern = re.compile(b"\xDE\xAD[\x40-\x4F].")
like image 178
John1024 Avatar answered Nov 12 '22 14:11

John1024