1 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
您缺少某些內(nèi)容,即r前綴:
r = re.compile(r"\\.") # Slash followed by anything
python和re將含義附加到\; 當(dāng)您將字符串值傳遞給時(shí)re.compile(),您加倍的反斜杠將變成一個(gè)反斜杠,此時(shí)re將看到\.,表示字面句號。
>>> print """\\."""
\.
通過使用r''您告訴python不要解釋轉(zhuǎn)義碼,因此現(xiàn)在re給了一個(gè)帶的字符串\\.,表示文字反斜杠后跟任何字符:
>>> print r"""\\."""
\\.
演示:
>>> import re
>>> s = "test \\* \\! test * !! **"
>>> r = re.compile(r"\\.") # Slash followed by anything
>>> r.sub("-", s)
'test - - test * !! **'
經(jīng)驗(yàn)法則是:在定義正則表達(dá)式時(shí),請使用r''原始字符串文字,從而使您不必對所有對Python和正則表達(dá)式語法均有意義的內(nèi)容進(jìn)行兩次轉(zhuǎn)義。
接下來,您要替換“轉(zhuǎn)義”字符;為此,請使用組,re.sub()讓您引用組作為替換值:
r = re.compile(r"\\(.)") # Note the parethesis, that's a capturing group
r.sub(r'\1', s) # \1 means: replace with value of first capturing group
現(xiàn)在的輸出是:
>>> r = re.compile(r"\\(.)") # Note the parethesis, that's a capturing group
>>> r.sub(r'\1', s)
'test * ! test * !! **'
添加回答
舉報(bào)