Python re.sub()行首开始锚定

Ada*_*tan 4 python regex string replace

考虑以下多行字符串:

>> 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.
Run Code Online (Sandbox Code Playgroud)

re.sub()替换所有的发生andAND:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

但是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.
Run Code Online (Sandbox Code Playgroud)

如何使用re.sub()start-of-line(^)或end-of-line($)锚点?

Ign*_*ams 12

您忘记启用多行模式.

re.sub("^and", "AND", s, flags=re.M)
Run Code Online (Sandbox Code Playgroud)

re.M
re.MULTILINE

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

资源

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

re.sub("(?m)^and", "AND", s)
Run Code Online (Sandbox Code Playgroud)


Ric*_*dle 7

添加(?m)多行:

print re.sub(r'(?m)^and', 'AND', s)
Run Code Online (Sandbox Code Playgroud)

请参阅此处的re文档.