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

前端 未结 3 1546
小蘑菇
小蘑菇 2020-11-22 10:12

The Python docs say:

re.MULTILINE: When specified, the pattern character \'^\' matches at the beginning of the string and at the beginning of each lin

3条回答
  •  一整个雨季
    2020-11-22 10:49

    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)
    

提交回复
热议问题