what would be the regular expression for null byte present in a string
Peter Otten
__peter__ at web.de
Tue Jan 13 09:41:51 EST 2015
Shambhu Rajak wrote:
> I have a string that I get as an output of a command as:
>
'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00\x00\x00\x00\x00\x00\x00\n'
>
> I want to fetch '10232ae8944a' from the above string.
>
> I want to find a re pattern that could replace all the \x01..\x0z to be
> replace by empty string '', so that I can get the desired portion of
> string
>
> Can anyone help me with a working regex for it.
I think you want the str.tranlate() method rather than a regex.
Assuming you are using Python 2:
>>> delenda = "".join(map(chr, range(32)))
>>> identity = "".join(map(chr, range(256)))
>>>
'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00\x00\x00\x00\x00\x00\x00\n'.translate(identity,
delenda)
'10232ae8944a'
With Python3:
>>> mapping = dict.fromkeys(range(32))
>>>
'\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x0010232ae8944a\x02\x00\x00\x00\x00\x00\x00\x00\n'.translate(mapping)
'10232ae8944a'
More information about the Python-list
mailing list