Get 10 numbers from the end of the string with Python regex?
Question: I have some strings like -

    
    
    1. "07870 622103"
    2. "(0) 07543 876545"
    3. "07321 786543 - not working"
    

I want to get the last 10 digits of these strings. like -

    
    
    1. "07870622103"
    2. "07543876545"
    3. "07321786543"
    

So far I have tried-

    
    
    a = re.findall(r"\d+${10}", mobilePhone)
    

Please help.


Answer: It'll be easier just to filter your string for digits and picking out the last
10:

    
    
    ''.join([c for c in mobilePhone if c.isdigit()][-10:])
    

Result:

    
    
    >>> mobilePhone = "07870 622103"
    >>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
    '7870622103'
    >>> mobilePhone = "(0) 07543 876545"
    >>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
    '7543876545'
    >>> mobilePhone = "07321 786543 - not working"
    >>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
    '7321786543'
    

The regular expression approach (filtering everything but digits), is faster
though:

    
    
    $ python -m timeit -s "mobilenum='07321 786543 - not working'" "''.join([c for c in mobilenum if c.isdigit()][-10:])"
    100000 loops, best of 3: 6.68 usec per loop
    $ python -m timeit -s "import re; notnum=re.compile(r'\D'); mobilenum='07321 786543 - not working'" "notnum.sub(mobilenum, '')[-10:]"
    1000000 loops, best of 3: 0.472 usec per loop
    

