不能在 re.sub() repr 表达式中的函数调用中使用 '\1' 反向引用来捕获组

Can't use '\1' backreference to capture-group in a function call in re.sub() repr expression

我有一个字符串 S = '02143' 和一个列表 A = ['a','b','c','d','e']。我想用列表 A.

中的相应元素替换 'S' 中的所有这些数字

例如,将0替换为A[0],将2替换为A[2]等。最终输出应该是 S = 'acbed'

我试过了:

S = re.sub(r'([0-9])', A[int(r'\g<1>')], S)

然而,这给出了一个错误 ValueError: invalid literal for int() with base 10: '\g<1>'。我猜它正在考虑将反向引用 '\g<1>' 作为字符串。我该如何解决这个问题,尤其是使用 re.sub 和捕获组,否则呢?

re.sub(r'([0-9])',A[int(r'\g<1>')],S) 不起作用的原因是 \g<1>(这是第一个反向引用的明确表示,否则写为 </code>)反向引用仅在用于 <em>字符串替换模式</em>。如果将它传递给另一个方法,它只会“看到”<code>\g<1> 文字字符串,因为那时 re 模块没有任何机会评估它。 re 引擎仅在匹配期间对其进行评估,但 A[int(r'\g<1>')] 部分在 re 引擎尝试查找匹配之前进行评估。

这就是为什么可以在 re.sub 中使用回调方法作为替换参数:您可以将匹配的组值传递给任何外部方法以进行高级操作。

参见 re documentation:

re.sub(pattern, repl, string, count=0, flags=0)

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.

使用

import re
S = '02143' 
A = ['a','b','c','d','e']
print(re.sub(r'[0-9]',lambda x: A[int(x.group())],S))

Python demo

请注意,您不需要 捕获 带有括号的整个模式,您可以使用 x.group().

访问整个匹配