Regex - Match string with or without suffix, but without including it in match group
<p>I'm currently trying to make a text message command server (basically, I send a text to google voice, that gets forwarded to my email, I use a python IMAP library to access the message, and I parse it), and I have an interesting problem. Sometimes, when a text comes through, the string </p>

<pre><code>--
Sent using SMS-to-email. Reply to this email to text the sender back and save on SMS fees.
https://www.google.com/voice/
</code></pre>

<p>is appended to the text message, which causes errors when parsing the command. Right now, to detect commands, I use the following regex (which is multiline and case-sensitive due to certain commands such as a timed send command that may use multiple lines):</p>

<pre><code>^/(randomfact) *(\S*)\s*$
</code></pre>

<p>But since the string telling me it was sent through SMS to email comes through once in a while, a match doesn't get detected. Using the <code>print</code> function of python, the message is shown as follows:</p>

<pre><code>/randomfact\r\n\r\n--\r\nSent using SMS-to-email. Reply to this email to text the sender back and  \r\nsave on SMS fees.\r\nhttps://www.google.com/voice/
</code></pre>

<p>Right now, to combat that issue, I have tried doing this:</p>

<pre><code>^/(randomfact)\s*(\d*)(?=\n\n--\nSent using SMS-to-email\. Reply to this email to text the sender back and save on SMS fees\.\nhttps://www\.google\.com/voice/)
</code></pre>

<p>But it only works if the string IS appended to the command. If it isn't, then the regex fails. My question is: Is there any way to exclude that string from any regex matches, whether it exists in the string or not?</p>

<p>If I understand your problem correctly, you are filtering out the optional signature of the message. In python you should be able to set the single line regex flag (i.e. <code>re.S</code>), and use the following regex to capture the desired content.</p>

<pre><code>regex = re.compile(r'(.+)(?=--)|(.+)', r.S)
</code></pre>

python regex