Iterate Previous Lines after find a pattern

I am searching for a pattern and then if I find that pattern(which can be multiples in a single file) then i want to iterate backwords and capture another pattern and pick the 1st instance.

For Example, if content of the file is as below:

SetSearchExpr("This is the Search Spec 1");
ExecuteQuery (ForwardOnly);
var Rec2=FirstRecord();

Then the Expected Output: ExecuteQuery Search Spec = “This is the Search Spec 1”

I have figured out by below to check if ExecuteQuery is present, but unable to get the logic to iterate back, my code as below:

import sys
import os
file = open("Sample_code.txt", 'r')
for line in file:
        if "ExecuteQuery (" in line:
            #if found then check previous lines for another pattern

If anyone help me with a steer then it would be of great help.


No need to go backwards. Just save the SetSearchExpr() line in a variable and use that when you find ExecuteQuery()

for line in file:
    if 'SetSearchExpr(' in line:
        search_line = line
    elif 'ExecuteQuery (' in line:
        m = re.match(r'SetSearchExpr((".*"))', search_line)
        search_spec =
        print(f'ExecuteQuery Search Spec = {search_spec}')