regex - Python re.sub() beginning-of-line anchoring -


consider following multiline string:

>> print s shall compare thee summer's day? thou art more lovely , more temperate rough winds shake darling buds of may, , summer's lease hath short date. 

re.sub() replaces occurrence of and and:

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

but re.sub() doesn't allow ^ anchoring beginning of line, adding causes no occurrence of and replaced:

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

how can use re.sub() start-of-line (^) or end-of-line ($) anchors?

you forgot enable multiline mode.

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

re.m
re.multiline

when specified, pattern character '^' matches @ beginning of string , @ beginning of each line (immediately following each newline); , pattern character '$' matches @ end of string , @ end of each line (immediately preceding each newline). default, '^' matches @ beginning of string, , '$' @ end of string , before newline (if any) @ end of string.

source

the flags argument isn't available python older 2.7; in cases can set directly in regular expression so:

re.sub("(?m)^and", "and", s) 

Comments