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
的定义:
re.sub(pattern, repl, string[, count, flags])
第 4 个参数是计数,您使用 re.MULTILINE
(即 8)作为计数,而不是作为标志。
要么使用命名参数:
re.sub('^//', '', s, flags=re.MULTILINE)
或者先编译正则表达式:
re.sub(re.compile('^//', re.MULTILINE), '', s)
关于带有标志的 Python re.sub 不会替换所有出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581/