2012-11-12 70 views
2

這似乎是一個簡單的問題,但顯然有一些我缺少的東西。Python RegEx匹配多行子字符串,但不會替換它

我有一個Python的功能設計,以取代自定義標籤之間發生的與HTML格式的代碼的代碼塊:

def subCode(text): 
    tags = re.findall('<<<mytag>>>.+?<<</mytag>>>', text, re.S) 
    for tag in tags: 
     match = re.search('>>>(.+?)<<<', tag, re.S) 
     replaced_code = replaceCode(match.group(1)) 
     text = re.sub(tag, replaced_code, text, re.S|re.M) 
    return text 

這將匹配落在標籤之間,就像這裏的代碼:

this is some 
random text 
<<<mytag>>>now this 
    is some 
    random code<<</mytag>>> 
and this is text again 

但是它並沒有用格式化替換代替代碼,並且返回的字符串與輸入相同。我錯過了什麼?

+0

當我運行你的例子時,它爲我工作。 –

回答

4

我想你想使用的re.sub()接受一個函數作爲第二個參數的變異,這是更簡單:

def subCode(text): 
    return re.sub('<<<mytag>>>(.+?)<<</mytag>>>', replaceFunc, text, flags=re.S) 

def replaceFunc(match): 
    return replaceCode(match.group(1)) 

如果第二個參數re.sub()是一個函數,它需要一個匹配對象輸入並且預計將返回替換字符串。

+0

工作完美!謝謝您的幫助! – woemler

相關問題