我想确保 re.sub
的 repl
参数是转义的,这样任何像 \1
这样的特殊序列都不会解释:
>>> repl = r'\1'
>>> re.sub('(X)', repl, 'X')
'X'
>>> re.sub('(X)', desired_escape_function(repl), 'X')
'\\1'
是否有一个函数可以做到这一点?我知道 re.escape
存在,应该使用这个吗?
最佳答案
不要为此目的使用re.escape
。 re.escape
用于 pattern
参数,而不是 repl
参数。
相反,请遵循 the advice of Python's documentation , 并手动将所有反斜杠替换为两个反斜杠:
>>> repl = r'\1'
>>> re.sub('(X)', repl.replace('\\', '\\\\'), 'X')
'\\1'
关于python - 转义 re.sub 的 repl 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49943270/