HansPeterLoft
HansPeterLoft

Reputation: 519

Python find messages inside a string mixed of ascii and hex

I try to find messages in a string mixed out of ascii which has the following format:

"212zp*    ���                �91238902Pressure_1,9472,Pressure_2,4251,is_usb: {0}478212zp+    ���                �91238902Pressure_1,9472,Pressure_2,4251,is_usb: {0}478212zp,    ���                �91238902Pressure_1,9472,Pressure_2,4251,is_usb: {0}478212zp-    ���               "

I need to decode both, the hex and the ascii messages. The messages are between 91238902 and 478212

How can I achieve this? The string is dynamic and can contain a undefined number of messages and also errors in the headers 91238902 and 478212 can occur

Upvotes: 0

Views: 197

Answers (1)

MattR
MattR

Reputation: 5146

This seems like a perfect use for a regular expression. here is a link to the pythex:

import re
x = "212zp*91238902Pressure_1,9472,Pressure_2,4251,is_usb:{0}478212zp+91238902Pressure_1,9472,Pressure_2,4251,is_usb: {0}478212zp,91238902Pressure_1,9472,Pressure_2,4251,is_usb: {0}478212zp-"

# will grab between 91238902 and 478212
# alternative regex is: (?<=91238902).*?(?=478212)
result = re.findall(r'91238902(.*?)478212', x)

output is a list:

['Pressure_1,9472,Pressure_2,4251,is_usb:{0}', 'Pressure_1,9472,Pressure_2,4251,is_usb: {0}', 'Pressure_1,9472,Pressure_2,4251,is_usb: {0}']

Upvotes: 2

Related Questions