【问题标题】:re.sub between two tagsre.sub 两个标签之间
【发布时间】:2015-03-23 01:16:09
【问题描述】:

我有以下字符串和要替换的替换文本:

original_text = '<title>Kramer vs. Kramer</title>'
replacement_text = "Kramer V Kramer"
--> '<title>Kramer V Kramer</title>'

如何通过正则表达式进行替换?到目前为止,我有:

re.sub(r'title>.+</title>', replacement_text, original_text)

但是,这是删除整个标签。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    使用环视。

    >>> original_text = '<title>Kramer vs. Kramer</title>'
    >>> replacement_text = "Kramer V Kramer"
    >>> re.sub(r'(?<=<title>).+?(?=</title>)', replacement_text, original_text, flags=re.S)
    '<title>Kramer V Kramer</title>'
    
    • (?&lt;=&lt;title&gt;)lookbehind 断言必须通过打开 title 标记来进行匹配。

    • .+? 将对一个或多个字符进行非贪婪匹配。

    • (?=&lt;/title) 断言匹配项后面必须跟结束标题标签。

    • flags=re.S 允许 . 跨行匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多