When you find the line containing Error
, you know that the line number containing the value is the current line number i
plus 2.
So store that line number in a variable, and when iterating check if the current line number is equal to that number. If the current line number is the one you have previously stored, you got the value:
value_line = None # initialize with a value that is not a valid line number
for i, line in enumerate(text.split('\n')):
if re.match(r"Error\s*:", line):
value_line = i + 2
if i == value_line: # this will happen in a later iteration
print(line) # this is the line containing the value
Alternatively, collect all lines in a list beforehand. Then you can directly access the desired line from the list and do not need to keep iterating:
lines = text.split('\n')
for i, line in enumerate(lines):
if re.match(r"Error\s*:", line):
print(lines[i + 2])
break # found the value, can stop iterating
Of course, instead of printing the line containing the value, you can do something else with it, for example split it and convert the first item to an integer.