16

How can I find the last number in any big string?

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: We don't know the number. The number 47 is just an example. It can be any number from 0 to 900.

jamylak
  • 128,818
  • 30
  • 231
  • 230
Mihir Kulkarni
  • 171
  • 1
  • 1
  • 4

2 Answers2

26
>>> 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]
Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230
2

I guess I don't know enough about the implementation details / performance of finding a bunch of results and choosing the last, vs just finding the last to begin with (didn't do any performance comparisons); but, this very well might be faster:

>>> 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>'
>>> import re
>>> re.search(r'(\d+)\D+$', text).group(1)
'47'
Matt Anderson
  • 19,311
  • 11
  • 41
  • 57
  • +1 I like this better than `re.findall`. I have a similar second version that I re-added to my answer which short circuits so it would be more efficient (not sure about speed) but this looks nicer – jamylak Jun 09 '13 at 08:37
  • Replace the '+'s with '*'s to also match the empty string and digits flush right, respectively. E.g., `re.search(r'(\d*)\D*$', '').group(1)` returns `''`. – gherson Aug 17 '19 at 22:09