Python re.sub MULTILINE caret match
<p>The Python docs say:</p>

<blockquote>
  <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p>
</blockquote>

<p>So what's going on when I get the following unexpected result?</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; s = """// The quick brown fox.
... // Jumped over the lazy dog."""
&gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'
</code></pre>

<p>Look at the definition of <a href="http://docs.python.org/library/re.html#re.sub"><code>re.sub</code></a>:</p>

<pre><code>sub(pattern, repl, string[, count])
</code></pre>

<p>The 4th argument is the count, you are using <code>re.MULTILINE</code> (which is 8) as the count, not as a flag.</p>

<p>You have to compile your regex if you wish to use flags.</p>

<pre><code>re.sub(re.compile('^//', re.MULTILINE), '', s)
</code></pre>

<p>A <code>flags</code> argument was added in Python 2.7, so the full definition is now:</p>

<pre><code>re.sub(pattern, repl, string[, count, flags])
</code></pre>

<p>Which means that:</p>

<pre><code>re.sub('^//', '', s, flags=re.MULTILINE)
</code></pre>

<p>works.</p>
