7

考虑以下多行字符串:

>> print s
shall i compare thee to a summer's day?
thou art more lovely and more temperate
rough winds do shake the darling buds of may,
and summer's lease hath all too short a date.

re.sub()替换所有出现的andwith AND

>>> print re.sub("and", "AND", s)
shall i compare thee to a summer's day?
thou art more lovely AND more temperate
rough winds do shake the darling buds of may,
AND summer's lease hath all too short a date.

re.sub()不允许^锚定到行首,因此添加它会导致没有and被替换:

>>> print re.sub("^and", "AND", s)
shall i compare thee to a summer's day?
thou art more lovely and more temperate
rough winds do shake the darling buds of may,
and summer's lease hath all too short a date.

如何re.sub()与行首 ( ^) 或行尾 ( $) 锚一起使用?

4

2 回答 2

21

您忘记启用多行模式。

re.sub("^and", "AND", s, flags=re.M)

re.M
re.MULTILINE

指定时,模式字符'^'匹配字符串的开头和每行的开头(紧跟在每个换行符之后);并且模式字符'$'在字符串的末尾和每行的末尾(紧接在每个换行符之前)匹配。默认情况下,'^'仅匹配字符串的开头、字符串'$'的结尾以及字符串末尾的换行符(如果有)之前。

资源

flags 参数不适用于 2.7 之前的 python;所以在这些情况下,您可以直接在正则表达式中设置它,如下所示:

re.sub("(?m)^and", "AND", s)
于 2013-07-15T07:39:42.663 回答
9

添加(?m)多行:

print re.sub(r'(?m)^and', 'AND', s)

请参阅此处的重新文档

于 2013-07-15T07:40:17.910 回答