2010-08-16 31 views
-1

我想要一個正則表達式匹配跨越多行的值。我正在使用re.S標誌,但仍然沒有結果。任何想法爲什麼?與多行正則表達式匹配的幫助

這就是我正在尋找通過文字:

<File id="abc.txt" EngRev="74"> 
    <Identifier id="STRING_ID" isArray="1" goesWith="3027253"> 
    <EngTranslation>"Value 1","Value 2","Value 3","Value 4","Value 5",</EngTranslation> 
    <LangTranslation filename="abc.txt" key="STRING_ID 0">Value 1</LangTranslation> 
    <array filename="abc.txt" key="STRING_ID 1">Value 2</array> 
    <array filename="abc.txt" key="STRING_ID 2">Value 3</array> 
    <array filename="abc.txt" key="STRING_ID 3">Value 4</array> 
    <array filename="abc.txt" key="STRING_ID 4">Value 5</array> 
    </Identifier> 
    <Identifier id="STRING_ID2" isArray="0" goesWith="3027253"> 
    <EngTranslation>"Value 1"</EngTranslation> 
    <LangTranslation filename="abc.txt" key="STRING_ID2">Value 1</LangTranslation> 
    </Identifier> 
</File> 

這是我使用來獲得比賽的代碼:

def updateToArray(matchobj): 
    return matchobj.group(0).replace('LangTranslation','array') 
outXML = re.sub(r'<Identifier.*?<array.*?</Identifier>', updateToArray, outXML, re.S) 
+3

重複http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – habnabit 2010-08-16 17:45:06

+4

不要使用正則表達式來解析XML。使用XML庫。 – Amy 2010-08-16 17:49:40

回答

7

我強烈建議你不要使用正則表達式解析XML。 SO有一個lotof問題/答案線索解釋了原因。例如見this classic

由於您使用Python爲什麼不使用庫,例如​​BeautifulSoupLxml來完成這項工作更加乾淨和簡潔?

+0

我只有7天活躍於SO。但是已經注意到每天大約有一個關於RE解析XML或HTML的問題。它應該在某個地方被捕獲爲常見的反模式。 – Odomontois 2010-08-16 20:20:23

1

你缺少變量:

re.sub(pattern, repl, string[, count, flags])

的標誌似乎是整數,所以它的治療re.S作爲count參數。對count使用零保留默認行爲並允許您將標誌作爲第五個參數傳遞。