正则表达式提取<b>和<strong>标记之间的文本

时间:2018-10-11 13:32:45

标签: python regex

我需要在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)

其中,labels是包含标签的此类html元素的列表。 预期的输出为['Features Windows 10','including VGA,']

取而代之的是:[('', 'Features Windows 10 Pro'), ('including VGA,', '')]

请帮助。预先感谢。

2 个答案:

答案 0 :(得分:6)

需要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,'

答案 1 :(得分:1)

第一个you should not use regexes to parse markup text

话虽这么说,结果是设计re.findall的文档对此非常明确(强调我的观点):

  

re.findall(模式,字符串,标志= 0)

     

以字符串列表形式返回字符串中所有不重复的模式匹配项。从左到右扫描该字符串,并以找到的顺序返回匹配项。如果该模式中存在一个或多个组,则返回一个组列表;否则,返回一个列表。 如果模式包含多个组,这将是元组列表

您的模式包含2组,一组用于<b>,一组用于<strong>。您将获得两个元组,以便您知道匹配的组。

如果您不喜欢这样做,则可以使用finditer来返回匹配对象。匹配对象上的group(0)是匹配的字符串的一部分:

text = [m.group() for m in pattern.finditer(label)]
相关问题