【问题标题】:How to replace one type of tag by another (<a ...>..</a> => <p>..</p>)如何用另一种类型的标签替换 (<a ...>..</a> => <p>..</p>)
【发布时间】:2017-02-22 15:18:09
【问题描述】:

我正在尝试弄清楚如何用&lt;p&gt;TEXT&lt;/p&gt; 标签替换所有&lt;a href....&gt;TEXT&lt;/a&gt; 标签。

我已经开始寻找&lt;a href...&gt;&lt;/a&gt; 的模式,所以我可以相应地替换它们。不幸的是,它似乎与最接近的字符串不匹配。

>>> s = '<td class="tt"><a href="#">Alert types</a></td>&#13;<td class="info">Vibration</td>&#13;      </tr><tr><td class="tt"><a href="#">Sound</a>'

>>> re.sub('<a h.*>','<p>',s)

返回

'<td class="tt"><p>'

代替:

 '<td class="tt"><p>Alert types</a></td>&#13;<td class="info">Vibration</td>&#13;      </tr><tr><td class="tt"><p>Sound</a>'

你知道如何让它匹配.*之间最接近的字符串吗?

【问题讨论】:

标签: python regex parsing


【解决方案1】:

使用以下方法:

s = '<td class="tt"><a href="#">Alert types</a></td>&#13;<td class="info">Vibration</td>&#13;      </tr><tr><td class="tt"><a href="#">Sound</a>'
replaced = re.sub(r'<a[^>]+?>([\w\W]+?)<\/a>', r'<p>\1</p>', s)

print(replaced)

输出:

<td class="tt"><p>Alert types</p></td>&#13;<td class="info">Vibration</td>&#13;      </tr><tr><td class="tt"><p>Sound</p>

【讨论】:

    【解决方案2】:

    不确定使用正则表达式是否是个好主意。但如果你更喜欢正则表达式,那么这里是:

    re.sub('<a [^>]*>([^<]*)</a>','<p>\\1</p>',s)
    

    使用([^&lt;]*) 捕获a 标记之间的文本,作为替换它使用组作为\\1

    【讨论】:

      【解决方案3】:

      这应该可行。

      搜索方式:

      (<.+?>)(.+)(<.+?>)
      

      输入:

      <a href="#">Sound</a>
      

      替换为:

      <p>$2</p>
      

      输出:

      <p>Sound</p>
      

      Python 代码:

      # coding=utf8
      # the above tag defines encoding for this document and is for Python 2.x compatibility
      
      import re
      
      regex = r"(<.+?>)(.+)(<.+?>)"
      
      test_str = "<a href=\"#\">Sound</a>"
      
      subst = "<p>$2</p>"
      
      # You can manually specify the number of replacements by changing the 4th argument
      result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
      
      if result:
          print (result)
      
      # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
      

      见:https://regex101.com/r/j4OsbX/1

      【讨论】:

        猜你喜欢
        • 2014-12-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 2018-06-06
        • 1970-01-01
        相关资源
        最近更新 更多