在替换字符串中的模式时,
我特别需要匹配命名组的整数/长值。
案例示例和我的尝试:
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')
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
关于python - Python : Convert named group to integer 中的正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925230/