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

时间:2012-03-29 12:24:05

标签: 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')

正常投射适用于原始字符串int(r'22'),但它在上面不起作用?

1 个答案:

答案 0 :(得分:7)

这应该适合你:

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

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