title: Python Regex to extract response from a modem AT command
body: <p>When sending a command to a modem, one usually sends a command (e.g. <code>AT</code>), followed by a <code>\r</code>. 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</p>
  
  <pre><code>AT\r\rOK\r\n
  </code></pre>
  
  <p>In case of an error it looks like</p>
  
  <pre><code>AT\r\rERROR\r\n
  </code></pre>
  
  <p>but in general, depending on the actual AT command, the returned value could be anything aside from <code>OK</code> and <code>ERROR</code>.</p>
  
  <p>I would like to extract this response, i.e. a regular expression that returns me the <code>OK</code>, the <code>ERROR</code> or whatever the modem replies. Here are the conditions:</p>
  
  <ul>
  <li>I want to verify the original command in the string, i.e. <code>ATX\r\rOK\r\n</code> should not match when the command was just <code>AT</code>.</li>
  <li>I do not care about how many whitespace characters are present at all, the only thing I expect is to have a <code>\n</code> at the end. So <code>AT\rOK\n</code> and <code>AT\nOK\r\r\n</code> should match as well, but not <code>AT\nOK\r\r</code>.</li>
  <li>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 <code>OK\rAT\rOK\n</code>  should match (i.e. the  right-side occurrence of <code>OK</code>), but <code>XAT\rOK\r\n</code> should not match. </li>
  </ul>
  
  <p>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:</p>
  
  <pre><code>r = re.compile("\s+AT\s+\w+\s*\\n$")
  </code></pre>
  
  <p>But how to extract what the <code>\w+</code> consists of?</p>