python - Python 正则表达式匹配失败
问题描述
这通过https://regex101.com/没有任何问题。我错过了什么吗?整个字符串在一行中。
def get_title_and_content(html):
html = """<!DOCTYPE html> <html> <head> <title>Change delivery date with Deliv</title> </head> <body> <div class="gkms web">The delivery date can be changed up until the package is assigned to a driver.</div> </body> </html> """
title_pattern = re.compile(r'<title>(.*?)</title>(.*)')
match = title_pattern.match(html)
if match:
print('successfully extract title and answer')
return match.groups()[0].strip(), match.groups()[1].strip()
else:
print('unable to extract title or answer')
解决方案
在评论摘要中:
title_pattern.search(html)
应该用来代替title_pattern.match(html)
因为搜索功能将搜索提供的字符串中的任何位置,而不是从头开始搜索。match = title_pattern.findall(html)
可以类似地使用,但会返回一个项目列表,而不仅仅是一个。
同样如前所述BeautifulSoup
,从长远来看,使用会付出更多代价,因为正则表达式不适合搜索 HTML
推荐阅读
- aws-codecommit - 尽管分配了 AWSCodeCommitFullAccess 策略,但仍无法访问 AWS CodeCommit
- django - django.core.exceptions.AppRegistryNotReady:应用程序尚未加载。用芹菜打
- sql - 选择子查询中的 NULLS
- r - 检查列表和条件变异的每个元素中是否存在变量
- encryption - Sql Server 2016 始终加密不工作
- typo3-7.6.x - Powermail 重定向不适用于双重选择
- symfony - 防止用户在表单中插入 HTML
- git - git 恢复删除的远程分支
- inheritance - 使用 Timber 嵌套块和多重继承
- java - 在 Java 8 中使用数组流计算单词出现次数