问题
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
回答1:
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].")
回答2:
I suspect you'll be best served by converting your binary string to an ASCII hexadecimal string, and applying your regex(s) to that. I don't believe regex's are intended to work with binary data; you might be able to get it to work, but don't be amazed if there are surprises along the way.
回答3:
If i were in your situation, i'd try hexdump with grep.
来源:https://stackoverflow.com/questions/20344679/python-regular-expression-search-pattern-for-binary-files-half-a-byte