考虑以下多行字符串:
>> 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()与行首 ( ^) 或行尾 ( $) 锚一起使用?