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

  • 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
up vote 13 down vote accepted

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.

  • 3
    Be wary this may cause issues on Windows. If it does, try \r\n instead of just \n. – Qix Apr 14 '15 at 20:55

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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