2012-10-12 29 views
2

Python正則表達式的專家!我正在嘗試在xml文檔中更改一行。 原線爲:使用Python正則表達式查找/替換文檔中的URL

<Tag name="low"  Value="%hello%\dir"/> 

我想看到的結果是:

<Tag name="low"  Value="C:\art"/> 

我未能直接的嘗試是:

lines = re.sub("%hello%\dir"", "C:\art"/> 

這是行不通的。不會更改文檔中的任何內容。有什麼%?

出於測試目的,我想:

lines = re.sub("dir", "C:\art", a) 

我也得到:

<Tag name="low"  Value="%hello%\C:BELrt"/> 

的問題是,\ A = BEL

我試了一堆其他的東西,但無濟於事。我該如何解決這個問題?

+0

你確定你需要正則表達式嗎?看起來你可以通過簡單的[replace()](http://docs.python.org/library/stdtypes.html#str.replace)方法調用? – ernie

回答

0

在Python中,使用字符串的r前綴來避免使用斜槓。然後逃避你的斜線,以避免\d匹配一個數字。

lines = re.sub(r"%hello%\\dir", r"C:\\art") 
+0

'r'\ d''表示匹配正則表達式中的數字 – jfs

+0

謝謝@J.F.Sebastian。我更新了我的答案。 – Philip

+0

'repl'部分中的'r'\ a'也應該被轉義。也''''' - >')' – jfs

0

你的問題是你有一些字符在正則表達式中有特定的含義。

\d表示任何數字。 %hello%\dir然後%hello%[0-9]ir

您需要逃生者斜線/使用原始字符串來解決這個問題:

a = '''<Tag name="low" Value="%hello%\dir"/>''' 
lines = re.sub(r"%hello%\\dir", r"C:\\art", a) 
print(lines) #<Tag name="low"  Value="C:\\art"/> 
0

這是一個很好的問題。它顯示了三個問題,一個文本表示一次:

  • '\a' Python的字符串文字是有獨鍾字符。

    要在Python源代碼中輸入反斜槓後跟字母'a',您需要使用原始文字:r'\a'或轉義斜槓'\\a'

  • r'\d'(兩個字符)在解釋爲正則表達式時具有特殊含義(r'\d'表示匹配正則表達式中的數字)。

    除了Python字符串文字的規則外,還需要轉義可能的正則表達式元字符。在一般情況下,您可以使用re.escape(your_string),或者僅使用r'\\d''\\\\d''\a'repl部分也應該被轉義(在你的情況下兩次:r'\\a''\\\\a'):

    >>> print xml.replace(old, new) 
    <Tag name="low"  Value="C:\art"/> 
    
  • >>> old, new = r'%hello%\dir', r'C:\art' 
    >>> print re.sub(re.escape(old), new.encode('string-escape'), xml) 
    <Tag name="low"  Value="C:\art"/> 
    

    順便說一句,你根本就不在這種情況下,需要正則表達式最後XML attribute value can't contain certain characters也應該逃過例如'&','"',"<"

一般而言,您不應該使用正則表達式來操作XML。 Python的stdlib具有XML解析器。

>>> import xml.etree.cElementTree as etree 
>>> xml = r'<Tag name="low"  Value="%hello%\dir"/>' 
>>> tag = etree.fromstring(xml) 
>>> tag.set('Value', r"C:\art & design") 
>>> etree.dump(tag) 
<Tag Value="C:\art &amp; design" name="low" /> 
+0

非常感謝!順便說一句,在'etree.fromstring(xml)'之後,所有的註釋都被忽略了。 如何用註釋解析XML文檔? –

+0

@RenataPre:[如何防止xml.ElementTree從字符串中刪除commentnode](http://stackoverflow.com/a/5411766/4279) – jfs