带有标志的Python re.sub不会replace所有的事件
Python文档说:
re.MULTILINE:指定时,模式字符'^'匹配string的开头和每行的开头(紧跟在每一个新行之后)…默认情况下,'^'只匹配string的开头…
那么当我得到以下意想不到的结果时发生了什么?
>>> 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.'  看看re.sub的定义: 
 sub(pattern, repl, string[, count]) 
 第四个参数是count,你正在使用re.MULTILINE (这是8)作为count,而不是一个标志。 
如果你想使用标志,你必须编译你的正则expression式。
 re.sub(re.compile('^//', re.MULTILINE), '', s) 
 在Python 2.7中添加了一个flags参数,所以完整的定义是: 
 re.sub(pattern, repl, string[, count, flags]) 
意思就是:
 re.sub('^//', '', s, flags=re.MULTILINE) 
作品。
 re.sub('(?m)^//', '', s) 
  re.sub的完整定义是: 
 re.sub(pattern, repl, string[, count, flags]) 
 这意味着如果你告诉Python参数是什么,那么你可以通过flags而不通过count : 
 re.sub('^//', '', s, flags=re.MULTILINE) 
或者更简洁:
 re.sub('^//', '', s, flags=re.M)