When sending a command to a modem, one usually sends a command (e.g. AT), followed by a \r. One then listens to the modem to see the result of the command, where this command itself is repeated. So a typical communication feedback from the modem looks like
AT\r\rOK\r\n
In case of an error it looks like
AT\r\rERROR\r\n
but in general, depending on the actual AT command, the returned value could be anything aside from OK and ERROR.
I would like to extract this response, i.e. a regular expression that returns me the OK, the ERROR or whatever the modem replies. Here are the conditions:
- I want to verify the original command in the string, i.e.
ATX\r\rOK\r\nshould not match when the command was justAT. - I do not care about how many whitespace characters are present at all, the only thing I expect is to have a
\nat the end. SoAT\rOK\nandAT\nOK\r\r\nshould match as well, but notAT\nOK\r\r. - Last, I do not care about extra stuff on the left side as long as they are separated from the AT command by whitespace characters. So
OK\rAT\rOK\nshould match (i.e. the right-side occurrence ofOK), butXAT\rOK\r\nshould not match.
Is it possible to do this with one single regex in order to extract the modem response, or do I need to make multiple regex searches? To see if the whole thing matches correctly at all, I might have found already an expression:
r = re.compile("\s+AT\s+\w+\s*\\n$")
But how to extract what the \w+ consists of?
You put
()around the part you want to extract, so your regex readsr"(?<!\S)AT\s+(\w+)\s*\n. You then get one group together with the match, that you can extract e.g. withgroup: