How can I detect last digits in python string

python-2.7, regex, string

Solution

Here is a method using `re.sub`:

import re

input = ['asdgaf1_hsg534', 'asdfh23_hsjd12', 'dgshg_jhfsd86']

for s in input:
    print re.sub('.*?([0-9]*)$',r'\1',s)

Output:

534
12
86

Explanation:

The function takes a `regular expression`, a `replacement string`, and the `string` you want to do the replacement on: `re.sub(regex,replace,string)`

The regex `'.*?([0-9]*)$'` matches the whole string and captures the number that precedes the end of the string. Parenthesis are used to capture parts of the match we are interested in, `\1` refers to the first capture group and `\2` the second ect..

.*?      # Matches anything (non-greedy) 
([0-9]*) # Upto a zero or more digits digit (captured)
$        # Followed by the end-of-string identifier 

So we are replacing the whole string with just the captured number we are interested in. In python we need to use raw strings for this: `r'\1'`. If the string doesn't end with digits then a blank string with be returned.

twosixfour = "get_the_numb3r_2_^_64__18446744073709551615"

print re.sub('.*?([0-9]*)$',r'\1',twosixfour)

>>> 18446744073709551615

Problem

I need to detect last digits in the string, as they are indexes for my strings. They may be 2^64, So it's not convenient to check only last element in the string, then try second... etc. String may be like `asdgaf1_hsg534`, i.e. in the string may be other digits too, but there are somewhere in the middle and they are not neighboring with the index I want to get.

Original source

Related problems