Python re.sub() 行首锚定

2023-12-23

考虑以下多行字符串:

>> 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()替换所有出现的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()不允许^锚定到行的开头,因此添加它不会导致出现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()与行首 (^) 或行尾 ($)锚点?


您忘记启用多行模式。

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

re.M
re.MULTILINE

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

source http://docs.python.org/2/library/re.html#re.M

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

re.sub("(?m)^and", "AND", s)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python re.sub() 行首锚定 的相关文章

随机推荐