我想用正则表达式从HTML页面中提取标题。目前我有这个:
title = re.search('<title>.*</title>', html, re.IGNORECASE).group()
if title:
title = title.replace('<title>', '').replace('</title>', '')
是否有正则表达式来提取<title>的内容,这样我就不必删除标签了?
我想用正则表达式从HTML页面中提取标题。目前我有这个:
title = re.search('<title>.*</title>', html, re.IGNORECASE).group()
if title:
title = title.replace('<title>', '').replace('</title>', '')
是否有正则表达式来提取<title>的内容,这样我就不必删除标签了?
当前回答
我需要一些东西来匹配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
其他回答
Try:
title = re.search('<title>(.*)</title>', html, re.IGNORECASE).group(1)
所提供的代码段不能处理异常 我可以建议
getattr(re.search(r"<title>(.*)</title>", s, re.IGNORECASE), 'groups', lambda:[u""])()[0]
默认情况下,如果没有找到模式或第一个匹配,则返回空字符串。
re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)
没有人建议使用前视和后视,有什么特别的原因吗?我在这里试图做完全相同的事情和(?<=<title>).+(?=<\/title>)工作得很好。它只会匹配括号之间的内容所以你不需要做整个组的事情。
我需要一些东西来匹配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