views:

1900

answers:

2

The Python docs say:

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...

So what's going on when I get the following unexpected result?

>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'
+14  A: 

Look at the definition of re.sub:

sub(pattern, repl, string[, count])

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

You have to compile your regex if you wish to use flags.

re.sub(re.compile('^//', re.MULTILINE), '', s)
Moe
it would be better to have `re.compile('^//', re.M).sub('', s)`
SilentGhost
+3  A: 
re.sub('(?m)^//', '', s)
Fompi