带标志的Python re.sub不会替换所有出现的事件

时间:2020-03-05 18:47:18  来源:igfitidea点击:

Python文档说:

re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the 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])

第四个参数是计数,我们使用的是" re.MULTILINE"(即8)作为计数,而不是标志。

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

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)