Python中的正则表达式替换:将命名组转换为整数

Pra*_*ush 3 python regex

在替换字符串中的模式时,
我特别需要匹配命名组的整数/长值.

案例和我尝试过的案例:

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')
Run Code Online (Sandbox Code Playgroud)

正常铸造适用于原始弦,int(r'22')但它在上面不起作用?

geo*_*org 7

这应该适合你:

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

如果repl是一个函数,则会为每个非重叠的模式调用调用它.该函数接受单个匹配对象参数,并返回替换字符串.@ http://docs.python.org/library/re.html#re.sub