2017-09-11 30 views
2

re.sub(pattern, repl, string, count=0, flags=0)如何使用應用re.sub由包含「 G」在Python

如DOC,如果REPL \g,Python會尋找下一個字符< REPL更換匹配。 不幸的是我需要repl包含\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&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) 
+0

雙逃避''\'''中\ g'(即' 「\\\\ G」'或'[R 「\\ g」') –

+0

@WiktorStribiżew正如我所說,我不能做'r'\\ g「'因爲repl是一個字符串變量,'re.escape(repl)'我會想得太多。使用re.escape時,我仍然沒有完全獲得我的代碼的行爲。我明天會看看它。 –

+0

您可以使用'my_repl.replace(r'\ g',r'\\ g')' –

回答

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)