Skip to content
Advertisement

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();
if(Rec2!=null);
{

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.

Advertisement

Answer

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 = m.group(1)
        print(f'ExecuteQuery Search Spec = {search_spec}')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement