如何使用re.sub将匹配项替换为包含'\g';用python

如何使用re.sub将匹配项替换为包含'\g';用python,python,regex,python-3.x,Python,Regex,Python 3.x,re.sub(模式、应答、字符串、计数=0、标志=0) 与文档中一样,如果repl中的\g,python将查找下一个字符,您需要确保替换字符串中的\g转换为\\g。此外,您实际上需要用两个反斜杠替换替换模式中的所有反斜杠,以防止出现进一步的问题 使用 见a: 双重转义\中的\(即“\\\\g”,或r“\\g”)@WiktorStribiżew,正如我所说的,我无法执行r“\\g”,因为repl是一个字符串变量,re.escape(repl)将转义太多。在使用re.escape时,我仍然不能完全理

re.sub(模式、应答、字符串、计数=0、标志=0)


与文档中一样,如果repl中的
\g
,python将查找下一个字符
,您需要确保替换字符串中的
\g
转换为
\\g
。此外,您实际上需要用两个反斜杠替换替换模式中的所有反斜杠,以防止出现进一步的问题

使用

见a:


双重转义
\
中的
\
(即
“\\\\g”
,或
r“\\g”
)@WiktorStribiżew,正如我所说的,我无法执行
r“\\g”
,因为repl是一个字符串变量,
re.escape(repl)
将转义太多。在使用re.escape时,我仍然不能完全理解代码的行为。我明天会看一看。您可以使用
my_repl.replace(r'\g',r'\\g')
@WiktorStribiżew谢谢。我想这可能有用。我明天早上试试。:-)谢谢@WiktorStribiżew它工作得很好。
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&amp;bg=ffffff&amp;fg=000000&amp;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&amp;bg=ffffff&amp;fg=000000&amp;s=0&amp;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)
rpl = rpl.replace('\\', '\\\\')
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)