Python regular expression to extract optional number at the end of string
Question: I'm trying to write a Python regular expression that can parse strings of the
type `"<name>(<number>)"`, where `<number>` is optional.

For example, if I pass `'sclkout'`, then there is no number at the end, so it
should just match `'sclkout'`. If the input is `'line7'`, then is should match
`'line'` and `'7'`. The name can also contain numbers inside it, so if I give
it `'dx3f'`, then the output should be `'dx3f'`, but for `'dx3b0'` it should
match `'dx3b'` and `0`.

This is what I first tried:

    
    
    import re
    
    def do_match(signal):
        match = re.match('(\w+)(\d+)?', signal)
        assert match
        print "Input = " + signal
        print "group1 = " + match.group(1)
        if match.lastindex == 2:
            print "group2 = " + match.group(2)
        print ""
    
    
    # should match 'sclkout'
    do_match("sclkout")
    
    # should match 'line' and '7'
    do_match("line7")
    
    # should match 'dx4f'
    do_match("dx4f")
    
    # should match 'dx3b' and '0'
    do_match("dx3b0")
    

This is of course wrong because of greedy matching in the `(\w+)` group, so I
tried setting that to non-greedy:

    
    
    match = re.match('(\w+?)(\d+)?', signal)
    

This however only matches the first letter of the string.


Answer: You don't need regex for this:

    
    
    from itertools import takewhile
    def do_match(s):
        num = ''.join(takewhile(str.isdigit, reversed(s)))[::-1]
        return s[:s.rindex(num)], num
    ... 
    >>> do_match('sclkout')
    ('sclkout', '')
    >>> do_match('line7')
    ('line', '7')
    >>> do_match('dx4f')
    ('dx4f', '')
    >>> do_match('dx3b0')
    ('dx3b', '0')
    

