Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace in Python: Convert named group to integer

Tags:

python

regex

While replacing a pattern in a string,
I specifically need the integer/long value of matching named group.

Example of case and what I 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 raw string int(r'22') but it doesn't work in above?

like image 651
Pratyush Avatar asked Oct 26 '25 19:10

Pratyush


1 Answers

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 every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. @ http://docs.python.org/library/re.html#re.sub

like image 71
georg Avatar answered Oct 29 '25 07:10

georg