Python 文档说:

重新多行:指定后,模式字符 '^' 匹配字符串的开头和每行的开头(紧跟在每个换行符之后)...默认情况下,“^”仅匹配字符串的开头...

那么,当我得到以下意外结果时,发生了什么事?

>>> 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])

第四个参数是计数,您正在使用 re.MULTILINE (即 8)作为计数,而不是作为标志。

如果您想使用标志,则必须编译正则表达式。

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

A flags Python 2.7 中添加了参数,所以现在完整的定义是:

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top