首页 > 解决方案 > 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')

标签: pythonregex

解决方案


在评论摘要中:

title_pattern.search(html)应该用来代替title_pattern.match(html)

因为搜索功能将搜索提供的字符串中的任何位置,而不是从头开始搜索。match = title_pattern.findall(html)可以类似地使用,但会返回一个项目列表,而不仅仅是一个。

同样如前所述BeautifulSoup,从长远来看,使用会付出更多代价,因为正则表达式不适合搜索 HTML


推荐阅读