【发布时间】:2019-10-18 02:24:05
【问题描述】:
对于html,我需要在img标签前后添加一个p标签。 每个 html 包含多个图像。
例如:
<br><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><br>
foo <img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""> foo
期望的结果:
<br><p><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><p><br>
foo <p><img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""><p> foo
我无法用正则表达式得到它。
我的失败代码:(test_str 是 html 字符串)
re.sub(r'(<img.*>)','<p>\\1<p>',test_str)
我的失败结果:
<br><p><img id="aimg_uhkH3" class="zoom" src="../Images/0001.jpg" border="0" alt="" width="430" height="20"><br><p>
foo <p><img id="acvdojj2" class="zoom" src="../Images/0002.jpg" width="430" height="20" border="0" alt=""><p> foo
有什么提示吗?提前致谢。
【问题讨论】:
-
试试
re.sub(r'(<img.*?>)','<p>\\1<p>',test_str)注意? -
如果您使用
<foo[^>]+>等,HTML 会更简单一些。