gpt4 book ai didi

Python Regex - 在 html 标签之间查找字符串

转载 作者:行者123 更新时间:2023-12-03 23:49:30 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Regex to find words between two tags

(3 个回答)


去年关闭。




我正在尝试提取 Html 标签之间的字符串。我可以看到之前已经在堆栈溢出中提出了类似的问题,但我对 python 完全陌生并且我正在挣扎。

所以如果我有

<b>Bold Stuff</b>

我想要一个正则表达式,让我有
Bold Stuff

但是到目前为止我所有的解决方案都给我留下了诸如
>Bold Stuff<

我真的很感激这方面的任何帮助。

我有
>.*?<

我已经看到一个关于堆栈溢出的问题和建议的解决方案
>([^<>]*)<

但这些都不适合我。请有人解释如何编写一个正则表达式,上面写着“找到我不包括 x 和 y 的字符 x 和 y 之间的字符串”。

谢谢你的帮助

最佳答案

>>> a = '<b>Bold Stuff</b>'
>>>
>>> import re
>>> re.findall(r'>(.+?)<', a)
['Bold Stuff']
>>> re.findall(r'>(.*?)<', a)[0] # non-greedy mode
'Bold Stuff'
>>> re.findall(r'>(.+?)<', a)[0] # or this, also is non-greedy mode
'Bold Stuff'
>>> re.findall(r'>(.*)<', a)[0] # greedy mode
'Bold Stuff'
>>>
此时,贪婪模式和非贪婪模式都可以工作。
您正在使用第一种非贪婪模式。下面是一个关于非贪婪模式和贪婪模式的例子:
>>> a = '<b>Bold <br> Stuff</b>'
>>> re.findall(r'>(.*?)<', a)[0]
'Bold '
>>> re.findall(r'>(.*)<', a)[0]
'Bold <br> Stuff'
>>>
这里是关于什么是 (...) :

(...)

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group;

the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below.

To match the literals ( or ), use \( or \), or enclose them inside a character class: [(] [)].

关于Python Regex - 在 html 标签之间查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33120584/

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