2013-04-13 27 views
-5

我想使用正則表達式從文本文件中找到一個部分。我有文件,如下:正則表達式來查找文本文件的特定部分

This is general text section that I don't want. 
HEADER:ABC1 
This is section text under header 
More text to follow 
Additional text to follow 
HEADER:XYZ2 
This is section text under header 
More text to follow 
Additional text to follow 
HEADER:KHJ3 
This is section text under header 
A match text will look like this A:86::ABC 

現在,我想檢索所有文字部分高達HEADER如果部分文本包含匹配A:86::ABC。結果文本將是

(HEADER:KHJ3 
This is section text under header 
A match text will look like this A:86::ABC). 

我感謝任何幫助。我使用python,並且匹配部分可以在文件中多於一個。這也是一個多行文件。

+0

您使用哪種編程語言? – user4035

回答

1
regex = re.compile(".*(HEADER.*$.*A:86::ABC)", re.MULTILINE|re.DOTALL) 
>>> regex.findall(string) 
[u'HEADER:KHJ3\nThis is section text under header \nA match text will look like this A:86::ABC'] 

希望這會有所幫助。 對於2次捕獲使用".*(HEADER.*$)(.*A:86::ABC)"

+0

謝謝!請請求你解釋正則表達式。 – user2277675

相關問題