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

前端 未结 3 1507
小蘑菇
小蘑菇 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:28
    re.sub('(?m)^//', '', s)
    
    0 讨论(0)
  • 2020-11-22 10:28

    The full definition of re.sub is:

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

    Which means that if you tell Python what the parameters are, then you can pass flags without passing count:

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

    or, more concisely:

    re.sub('^//', '', s, flags=re.M)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题