I am searching for a regex expression to match couple of lines over the matched line. For example:


I would like to capture the 2 lines above the XXXXXXXX.

Any help would be appreciated. Note: with Python using library re

  • 1
    Using what software? Different programs have different ideas about what a regexp is. – David Richerby Apr 11 '15 at 13:00
  • Using Python specifically or in any tool/language? – kenorb Apr 11 '15 at 13:14
  • If you are using python, it might be better to dump the whole into an array, where each row is its own element. You then loop through the array, finding XXXXXXXX, once found use the index of that item -1 and -2 to get the lines. – LPChip Apr 11 '15 at 13:27
  • hi man thanks for the advice, i did it already with a for loop but wondering how to do with regex – takobaba Apr 11 '15 at 14:35

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


  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.

  • 4
    Be wary this may cause issues on Windows. If it does, try \r\n instead of just \n. – Qix - MONICA WAS MISTREATED Apr 14 '15 at 20:55
  • 1
    Of course, this will match only a line that begins with XXXXXXXX (but it doesn't necessarily end with XXXXXXXX). – G-Man Says 'Reinstate Monica' Mar 8 '20 at 23:52

Adding to erikgaal`s answer, use an extra .* before xxxxxx,to match any tabs/white spaces.


  • 1
    Well, .* won't match just tabs/spaces; it will match anything (e.g., "The quick brown XXXXXXX"). – G-Man Says 'Reinstate Monica' Mar 8 '20 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.