So I am looking at parsing through a code using regular expressions and am wondering if there is an easier way to do it than what I have so far. I'll start with an example of a string I would be parsing through:
T16F161A286161990200040000\r (It's data coming through a serial device)
Now first I need to check the confirmation code, which are the first 9 characters of the code. They need to be exactly T16F161A2. If those 9 characters match exactly, I need to check the next 3 chracters which need to be either 861 or 37F.
If those 3 characters are 37F I have it do something I still need to code, so we won't worry about that result.
However if those 3 characters are 861 I need it to check the 2 characters after those and see what they are. They can be 11, 14, 60, 61, F0, F1, or F2. Each one of these does different things with the data preceeding it.
Finally I need to loop through the remaining characters, pairing each 2 of them together.
For an example of how this works, here is the code I've thrown together to parse through the example string I posted above:
import re
test_string = "T16F161A286161990200040000\r"
if re.match('^T16F161A2.*', test_string):
print("Match: ", test_string)
test_string = re.sub('^T16F161A2', '', test_string)
if re.match('^861.*', test_string):
print("Found '861': ", test_string)
test_string = re.sub('^861', '', test_string)
if re.match('^61.*', test_string):
print("Found '61' : ", test_string)
test_string = re.sub('^61', '', test_string)
for i in range(6):
if re.match('^[0-9A-F]{2}', test_string):
temp = re.match('^[0-9A-F]{2}', test_string).group()
print("Found Code: ", temp)
test_string = re.sub('^[0-9A-F]{2}', '', test_string)
Now as you can see in this code, after every step I am using re.sub() to remove the part of the string I had just been looking for. With that in mind my question is the following:
Is there a way to parse the string and find the data I need, while also keeping the string intact? Would it be more or less efficient that what I currently have?
if/elifstatements.if/elifstatements or adict.