Python 3查找字符串中的最后一个数字
问题描述:
如何找到任何大字符串中的最后一个数字?
How can I find the last number in any big string?
例如,在以下字符串中,我希望输出47:
For eg in the following string I want 47 as the output:
'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
PS:我们不知道这个电话号码.数字47只是一个例子.可以是0到900之间的任何数字.
PS: We don't know the number. The number 47 is just an example. It can be any number from 0 to 900.
答
>>> import re
>>> text = 'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
>>> re.findall(r'\d+', text)[-1]
'47'
如果您需要匹配浮点,则总是有此
If you need to match floating points there's always this
对于很长的字符串,这会更有效:
For very long strings this is more efficient:
re.search(r'\d+', text[::-1]).group()[::-1]