Consider the following multiline string:
>> 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()
replaces all the occurrence of and
with 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.
But re.sub()
doesn't allow ^
anchoring to the beginning of the line, so adding it causes no occurrence of and
to be replaced:
>>> 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.
How can I use re.sub()
with start-of-line (^
) or end-of-line ($
) anchors?
You forgot to enable multiline mode.
source
The flags argument isn't available for python older than 2.7; so in those cases you can set it directly in the regular expression like so:
Add
(?m)
for multiline:See the re documentation here.