我有一个具有以下模式的字符串。字符串将始终保持不变。只是数字会有所不同
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句