Python re.sub with a flag does not replace all occurrences

Look at the definition of re.sub:

re.sub(pattern, repl, string[, count, flags])

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

Either use a named argument:

re.sub('^//', '', s, flags=re.MULTILINE)

Or compile the regex first:

re.sub(re.compile('^//', re.MULTILINE), '', s)

Leave a Comment