You can use the start index of the match object to find the previous and next EOL using str.find
and str.rfind
with their start
and end
parameters:
with open ('test.txt', 'rt') as myfile:
contents = myfile.read()
match = re.search("abc", contents)
start = match.start()
previous_EOL = contents.rfind('\n', 0, start)
next_EOL = contents.find('\n', start)
line = contents[previous_EOL+1: next_EOL]
For example:
contents = '''
This is a sample text
Here is 'abc' in this line.
There are some other lines.'''
match = re.search("abc", contents)
start = match.start()
previous_EOL = contents.rfind('\n', 0, start)
next_EOL = contents.find('\n', start)
line = contents[previous_EOL+1: next_EOL]
print(line)
Prints:
Here is 'abc' in this line.