How to capture a couple of lines around a regex match?
I am searching for a regex expression to match couple of lines over the matched line. For example:
ABCDEFGHADEFGH
ABCDEFGHADEFGH
ABCDEFGHDEFGHABCDEFGH
ABCDEFGHDEFGHABCDEFGH
ABCDEFGHABCDEFGHABCDEFGH
ABCDEFGHABCDEFGHABCDEFGH
XXXXXXXX
I would like to capture the 2 lines above the XXXXXXXX.
Any help would be appreciated. Note: with Python using library re
The following RegEx tests for a variable amount of lines before the XXXXXXXX
line and returns them in the first capture group.
((.*(\n|\r|\r\n)){2})XXXXXXXX
-
(.*(\n|\r|\r\n))
tests for a string ending with a newline. (\n
for Unix,\r
for old Mac OS,\r\n\
for Windows) -
{2}
quantifies this 2 times. -
()
around that makes sure all lines come in one capture group. -
XXXXXXXX
is the string that the text has to end with.
Now in Python, you can use p.match(regex)[0]
to return the first capture group.