-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,匹配部分在一个文件中可以有多个。这也是一个多行文件。

4

1 回答 1

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)"

于 2013-04-13T17:14:37.177 回答