[英]Regex to extract text between <b> and <strong> tag
我需要在python中使用正则表达式提取介于和标记之间的文本。
示例: Customizable:<strong>Features Windows 10 Pro</strong> and legacy ports <b>including VGA,</b> HDMI, RJ-45, USB Type A connections.
为此,我正在做:
pattern=re.compile("(<b>(.*?)</b>)|(<strong>(.*?)</strong>)")
for label in labels:
print(label)
flag=0
if(('Window'in label or 'Windows' in label) and ('<b>' in label or '<strong>' in label)):
text=re.findall(pattern, label)
print(text)
标签是包含标签的此类html元素的列表。 预期的输出为['Features Windows 10','including VGA,']
取而代之的是: [('', 'Features Windows 10 Pro'), ('including VGA,', '')]
请帮忙。 提前致谢。
喜欢BeautifulSoup吗?
from bs4 import BeautifulSoup
data = BeautifulSoup("""Customizable:<strong>Features Windows 10 Pro</strong> and legacy ports <b>including VGA,</b> HDMI, RJ-45, USB Type A connections""")
data.find_all('strong')[0].text
data.find_all('b')[0].text
输出量
Features Windows 10 Pro
'including VGA,'
首先, 您不应该使用正则表达式来解析标记文本 。
就是说,结果是设计使然 。 re.findall
的文档re.findall
非常明确(强调我的观点):
re.findall(模式,字符串,标志= 0)
返回字符串中模式的所有非重叠匹配项,作为字符串列表。 从左到右扫描该字符串,并以找到的顺序返回匹配项。 如果该模式中存在一个或多个组,则返回一个组列表;否则,返回一个列表。 如果模式具有多个组,则这将是一个元组列表 。
您的模式包含2个组,一组用于<b>
,一组用于<strong>
。 您将获得两个元组,以便您知道匹配的组。
如果您不喜欢它,可以使用finditer
代替,它将返回一个match对象。 匹配对象上的group(0)
是匹配的字符串的一部分:
text = [m.group() for m in pattern.finditer(label)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.