Skip to main content
 首页 » 编程设计

python之如何使用正则表达式从字符串中获取数字

2025年05月04日18birdshome

我有一个具有以下模式的字符串。字符串将始终保持不变。只是数字会有所不同

Showing Results (1 – 15 of 96,831) 

我想从该字符串中提取 96,831。我想用正则表达式来做到这一点。什么可以是正则表达式?我尝试了一种使用两个正则表达式但仍未获得所需数量的方法。

"Showing Results (1 – 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ – \d+)/g, '') 

它的输出如下。此输出包含不需要的空格。

"    96,831" 

我想要一种在 python 中执行此操作的方法。谁能帮帮我?

请您参考如下方法:

在这种情况下,您应该避免使用正则表达式,因为它只需要简单的 strip 和 split,如下所示:

>>> s = 'Showing Results (1 – 15 of 96,831)' 
>>> num = s.split()[-1] 
'96,831)' 
>>> num.strip(')') 
'96,831' 

或者,使用 str.rstrip:

>>> num = s.rsplit(maxsplit=1)[-1] 
>>> num 
'96,831)' 
>>> num.strip(')') 
'96,831' 

但是如果你坚持使用正则表达式,那么这个模式可能会为你完成工作:

>>> import re 
>>> nums = re.findall(r'\d+,?\d*', s) 
['1 ', '15 ', '96,831'] 
>>> nums[-1] 
'96,831' 

如果您想将其转换为float,请不要忘记将, 替换为。:

>>> num 
'96,831' 
>>>  
>>> num = num.replace(',','.') 
>>> num 
'96.831' 
>>> float(num) 
96.831