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. Apr 11, 2015 at 13:00
  • Using Python specifically or in any tool/language?
    – kenorb
    Apr 11, 2015 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, 2015 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, 2015 at 14:35

2 Answers 2


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


  1. (.*(\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. {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. Apr 14, 2015 at 20:55
  • 1
    Of course, this will match only a line that begins with XXXXXXXX (but it doesn't necessarily end with XXXXXXXX). Mar 8, 2020 at 23:52

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


  • 2
    Well, .* won't match just tabs/spaces; it will match anything (e.g., "The quick brown XXXXXXX"). Mar 8, 2020 at 23:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .