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

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

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


当前回答

re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)

其他回答

在regexp中使用(),在python中使用group(1)来检索捕获的字符串(re.search如果没有找到结果将返回None,所以不要直接使用group()):

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

if title_search:
    title = title_search.group(1)

请注意,从Python 3.8开始,并引入了赋值表达式(PEP 572)(:=操作符),可以通过直接在if条件中捕获匹配结果作为变量并在条件体中重用它来改进Krzysztof krasosco的解决方案:

# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
  title = match.group(1)
# hello

尝试使用捕获组:

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

我可以向您推荐美丽汤吗?Soup是一个解析所有html文档的很好的库。

soup = BeatifulSoup(html_doc)
titleName = soup.title.name

我需要一些东西来匹配package-0.0.1(名称,版本),但想拒绝一个无效的版本,如0.0.010。

参见regex101示例。

import re

RE_IDENTIFIER = re.compile(r'^([a-z]+)-((?:(?:0|[1-9](?:[0-9]+)?)\.){2}(?:0|[1-9](?:[0-9]+)?))$')

example = 'hello-0.0.1'

if match := RE_IDENTIFIER.search(example):
    name, version = match.groups()
    print(f'Name:     {name}')
    print(f'Version:  {version}')
else:
    raise ValueError(f'Invalid identifier {example}')

输出:

Name:     hello
Version:  0.0.1