【问题标题】:Python re.sub() beginning-of-line anchoringPython re.sub() 行首锚定
【发布时间】:2013-07-13 00:11:43
【问题描述】:

考虑以下多行字符串:

>> 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 替换为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() 与行首 (^) 或行尾 ($) 锚点一起使用?

【问题讨论】:

    标签: python regex string replace


    【解决方案1】:

    您忘记启用多行模式。

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

    re.M
    re.MULTILINE

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

    source

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

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

    【讨论】:

      【解决方案2】:

      为多行添加(?m)

      print re.sub(r'(?m)^and', 'AND', s)
      

      the re documentation here

      【讨论】:

        猜你喜欢
        • 2018-04-29
        • 2015-11-08
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多