Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regexp for data of byte numbers

Tags:

python

regex

How to make a regexp matching for a row of bytes?
For example how to check with regexp that binary data consists of (0-10 byte) characters?

data = 0x00 0x05 0x02 0x00 0x03 ... (not a string, binary data)

like image 551
Sergey Avatar asked Aug 23 '26 02:08

Sergey


2 Answers

If you want to check that the string contains only characters between chr(0) and chr(10), simply use

re.match('^[\0-\x0A]*$',data)

For Python3, you can do the same with byte strings:

re.match(b'^[\0-\x0A]*$',b'\x01\x02\x03\x04')
like image 98
grep Avatar answered Aug 25 '26 17:08

grep


This will match any code before space:

if re.search('[\0-\037]', line):
    # Contains binary data...

I'm not sure what you mean by "0-10 byte", but if you mean that you want to match only the byte values 0 to 10, then replace \037 with \012 in the above code.

Note that 0-10 aren't really the only codes that would suggest binary data; anything below \040 or above \0177 usually suggests binary data.

like image 38
Marcelo Cantos Avatar answered Aug 25 '26 15:08

Marcelo Cantos