0

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

Van Peer
  • 2,127
  • 2
  • 25
  • 35
HansPeterLoft
  • 489
  • 1
  • 9
  • 28

1 Answers1

2

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}']
MattR
  • 4,887
  • 9
  • 40
  • 67
  • Thank you, that works perfect. How can I erease the messages from the string I read with .findall? – HansPeterLoft Nov 02 '17 at 16:36
  • @HansPeterLoft, My Pleasure! If this has answered your question, please mark this answer as accepted (only if it was answered). Can you give me clarification on what you mean by `"erase messages you read"`? – MattR Nov 02 '17 at 16:50
  • The string I reading the data from is a serial port and I append all the data I read to the string x in your example. Since the data may only arrive half when I do check for messages, I cannot throw away x after reading out the messages, but I would like to erease the messages from x I have already read. – HansPeterLoft Nov 02 '17 at 17:12
  • I would try coming up with some `not in` logic. If you append to a list of messages you have already read, you can compare the two lists. [this question] (https://stackoverflow.com/questions/2104305/finding-elements-not-in-a-list) for an example. In psuedo code it would be `if thing in one list is in the other- pass. Else - Read` – MattR Nov 02 '17 at 17:38