Regex将数字提取到组中

Regex extract numer into group

本文关键字:提取 数字 Regex      更新时间:2023-09-26

我有一个简单的html代码:

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

或者可能是:

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

我使用了(('d+'.'d+)|('d+)) star,但它提取了我三组,我需要一个有数值的。

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

谢谢!

尝试删除内部括号:

('d+'.'d+|'d+) star

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

您可以通过添加?使组不捕获:在像这个一样打开支架之后

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

但在你的情况下不需要你的内括号。

您可以将表达式重写为

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

在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']