You can use regex
here:
>>> import re
>>> s = "askdfghj... Hello world my name is Alex and I am 18 years all ...askdfgj."
>>> re.search(r'my.*Alex', s).group()
'my name is Alex'
If string contains multiple Alex
after my
and you want only the shortest match then use .*?
:
With ?
:
>>> s = "my name is Alex and you're Alex too."
>>> re.search(r'my.*?Alex', s).group()
'my name is Alex'
Without ?
:
>>> re.search(r'my.*Alex', s).group()
"my name is Alex and you're Alex"
Code:
with open('infile') as f1, open('outfile', 'w') as f2:
data = f1.read()
match = re.search(r'my.*Alex', data, re.DOTALL)
if match:
f2.write(match.group())