python - 提取正则表达式匹配的一部分

标签 python html regex html-content-extraction

我想要一个正则表达式来从 HTML 页面中提取标题。目前我有这个:

title = re.search('<title>.*</title>', html, re.IGNORECASE).group()
if title:
    title = title.replace('<title>', '').replace('</title>', '') 

是否有正则表达式可以仅提取 <title> 的内容,这样我就不必删除标签?

最佳答案

在正则表达式和 group(1) 中使用 ( )在python中检索捕获的字符串(re.search如果找不到结果将返回None,所以不要直接使用group()):

title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)

关于python - 提取正则表达式匹配的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1327369/

相关文章:

jquery - 从 JSON 数据创建联系人表

python - 与正则表达式相关的CountVectorizer预处理

javascript - REGEX:添加一个模式以在某些情况下与我的模式不匹配

python - Numpy:如何检查数组是否包含某些数字?

python - 如何提取在 python 中渲染 HTML 页面期间获得的 url 列表?

python - 编译网页表单并使用 Mechanize 检索文件

regex - Raku:在正则表达式中使用主题变量(来自 'for' )

python - 将带有嵌套括号的字符串转换为嵌套列表,python

python - opencv python视频旋转

jquery - 如何使用垂直导航显示/隐藏图像