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

2024-06-04

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

案例示例和我尝试过的方法:

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')但它在上面不起作用?


这应该适合你:

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 http://docs.python.org/library/re.html#re.sub

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐