首页 > 解决方案 > 用正则表达式提取子字符串,总是没有 re.match()

问题描述

我想通过正则表达式从字符串中提取一些信息,但结果总是无。源代码如下:

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
x = re.match(r'property=".+?"',line)
print(x)

我想提取内容和属性元组,我该如何解决?

标签: pythonregex

解决方案


我会建议一些更合适的东西。

使用beautifulsoup

from bs4 import BeautifulSoup

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
soup = BeautifulSoup(line, 'lxml')

print("Content: {}".format(soup.meta["content"]))
print("Property: {}".format(soup.meta["property"]))

输出

Content: Allrecipes
Property: og:site_name

推荐阅读