正则表达式提取数字到组中

2024-04-20 13:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有简单的html代码:

<span class="someclass" title="4.5 stars"></span>

或者可能是:

<span class="someclass" title="5 stars"></span>

我用了((\d+\.\d+)|(\d+)) star,但它提取了我3组,我需要一个数字值。你知道吗

如何在一个组中使用Regex提取两个字符串中的4.5和5?你知道吗

谢谢!你知道吗


Tags: 字符串代码titlehtml数字classregexstar
3条回答

在python中可以这样做:

import re

txt = '<span class="someclass" title="4.5 stars"></span>, <span class="someclass" title="5 stars"></span>'
re.findall(r'\d+[.]\d+|\d+', txt)

['4.5', '5']

尝试删除内圆括号:

(\d+\.\d+|\d+) star

另外,您可能希望考虑首先使用HTML解析器来提取属性,而不是将正则表达式直接应用于原始HTML。你知道吗

您可以通过添加一个?:在像这样的开始括号之后

((?:\d+\.\d+)|(?:\d+)) star

但你的情况下不需要你的内支架。你知道吗

你可以把你的表达改写成

(\d+(?:\.\d+)?) star

相关问题 更多 >