re.sub(pattern, repl, string, count=0, flags=0)
如文档中所示,如果 \g在 repl 中,python 将寻找下一个字符 < . 不幸的是我需要 repl contain \g ,我不能把原始字符串 r'repl_string'在 repl 的位置,因为它是一个字符串变量。如果我输入 re.escape('repl_string') 它可以工作,但结果不是我想要的,因为它转义了大部分字符。
我该怎么办?
这是我实际拥有的代码:
newline = '<p align="center"><img src="https://s0.wp.com/latex.php?latex=%5Cdisplaystyle+%7B%5Cbf+P%7D%28+%7C%5Cfrac%7BS_n+-+n+%5Cmu%7D%7B%5Csqrt%7Bn%7D+%5Csigma%7D%7C+%5Cgeq+%5Clambda+%29+%5C+%5C+%5C+%5C+%5C+%282%29&bg=ffffff&fg=000000&s=0" alt="\\displaystyle {\x08f P}( |\x0crac{S_n - n \\mu}{\\sqrt{n} \\sigma}| \\geq \\lambda ) \\ \\ \\ \\ \\ (2)" title="\\displaystyle {\x08f P}( |\x0crac{S_n - n \\mu}{\\sqrt{n} \\sigma}| \\geq \\lambda ) \\ \\ \\ \\ \\ (2)" class="latex" width="173" height="38" srcset="https://s0.wp.com/latex.php?latex=%5Cdisplaystyle+%7B%5Cbf+P%7D%28+%7C%5Cfrac%7BS_n+-+n+%5Cmu%7D%7B%5Csqrt%7Bn%7D+%5Csigma%7D%7C+%5Cgeq+%5Clambda+%29+%5C+%5C+%5C+%5C+%5C+%282%29&bg=ffffff&fg=000000&s=0&zoom=2 2x" scale="2">'
re.sub(r'<img.*?>', '\\[ {\\bf P}( |\\frac{S_n - n \\mu}{\\sqrt{n} \\sigma}| \\geq \\lambda ) \\ \\ \\ \\ \\ (2)\\]', newline, count = 1)
请您参考如下方法:
您需要确保替换字符串中的 \g 变成了 \\g。此外,您实际上需要用两个反斜杠替换替换模式中的所有反斜杠,以防止出现进一步的问题。
使用
rpl = rpl.replace('\\', '\\\\')
查看 demo :
import re
rpl = r'\geq \1'
# print(re.sub(r'\d+', rpl, 'Text 1')) # sre_constants.error: missing group name
# print(re.sub(r'\d+', r'some \1', 'Text 1')) # sre_constants.error: invalid group reference
print(re.sub(r'\d+', rpl.replace('\\', '\\\\'), 'Text 1')) # => Text \geq \1 (as expected)
