gpt4 book ai didi

python - 正则表达式 - 如何获取该字符串中的最后一个标签

转载 作者:行者123 更新时间:2023-12-02 01:25:10 25 4
gpt4 key购买 nike

我有一个字符串

"<li style="-moz-float-edge: content-box">... that in <i><b><a href="/wiki/La%C3%9Ft_uns_sorgen,_la%C3%9Ft_uns_wachen,_BWV_213" title="Lat uns sorgen, lat uns wachen, BWV 213">Die Wahl des Herkules</a></b></i>, Hercules must choose between the good cop and the bad cop?<br style="clear:both;" />" 

我想获取最后一个标签

"<br style="clear:both;" />"

我的重新 - r'[<]([\w]+\b)(.^<)+[/][>]'不起作用。我希望通过排除 '<' 来找到匹配项符号。

https://regex101.com/r/BDD30S/1

最佳答案

注意:使用正则表达式解析 HTML 是一个糟糕的主意!

但是,我无法抗拒挑战,所以这里是:

import re

haystack = '<li style="-moz-float-edge: content-box">... that in <i><b><a href="/wiki/La%C3%9Ft_uns_sorgen,_la%C3%9Ft_uns_wachen,_BWV_213" title="Lat uns sorgen, lat uns wachen, BWV 213">Die Wahl des Herkules</a></b></i>, Hercules must choose between the good cop and the bad cop?<br style="clear:both;" />'

needle = r'(<[^<>]*>)'
matches = re.findall(needle, haystack)
if matches:
print(matches[-1])

此代码查找最后一个非嵌套标签。如果元素有 < ,它会严重失败或>其属性或文本内容中的任何位置。如果某个元素有一个开始标签和一个结束标签,则只会找到结束标签。

<br style="clear:both;" />

关于python - 正则表达式 - 如何获取该字符串中的最后一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74884772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com