Skip to content Skip to sidebar Skip to footer

Python Regex - Capture Match And Previous Two Lines

In reference to a previous question Python data extract from text file - script stops before expected data match How can I capture a match and the previous two lines? I tried this

Solution 1:

You may use

re.findall(r'(?:.*\r?\n){2}.*random data.*', s)

Note you can't use re.DOTALL or .* will match up to the end of the input and you will only get the last occurrence.

See the Python demo

Pattern details

  • (?:.*\r?\n){2} - 2 occurrences of a sequence of
    • .* - any 0+ chars other than line break chars, as many as possible (a line)
    • \r?\n - a line ending (CRLF or LF)
  • .*random data.* - a line containing random data substring.

See the regex demo.

Post a Comment for "Python Regex - Capture Match And Previous Two Lines"