How to capture a couple of lines around a regex match

pythonregex

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

Best Answer

The following RegEx tests for a variable amount of lines before the XXXXXXXX line and returns them in the first capture group.

((.*\n){2})XXXXXXXX

  1. (.*\n) tests for a string ending with \n, a newline.
  2. {2} quantifies this 2 times.
  3. () around that makes sure all lines come in one capture group.
  4. 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.

Related Question