Regex replace in Python: convert named group to integer

When replacing a pattern in a string,
I especially need an integer / long value to match a named group.

Example case and what I've tried:

status = {1:'foo', 23:'bar'}
re.sub(
    '<status>(?P<id>\d+)',
    status.get(int(r'\g<id>')), # ValueError: invalid literal for int() with base 10: '\\g<id>'
    # status.get(int(r'\g<id>'.decode())), # ValueError: invalid literal for int() with base 10: '\\g<id>'
    # status.get('%d' % r'\g<id>'), # %d format: a number is required, not str
    'Tom ran: from <status>1 to <status>23')

      

Normal casting works well with original string int(r'22')

, but doesn't it work above?

+3


source to share


1 answer


This should work for you:

re.sub(
    '<status>(?P<id>\d+)',
    lambda m: status.get(int(m.group('id'))),
    'Tom ran: from <status>1 to <status>23')

      



If repl is a function, it is called for each non-overlapping occurrence of the pattern. The function takes one argument of the matching object and returns the replacement string. @ http://docs.python.org/library/re.html#re.sub

+7


source







All Articles