How to capture a couple of lines around a regex match?

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.

Tags:

Python

Regex