import re
regex = re.compile(r"<ROW[^<]*?>[^<]*<TO>(?=[^<]*412)[^<]*<\/TO>.*?<\/ROW>", flags=re.DOTALL | re.MULTILINE)
test_str = ("<ROW num=\"381\">\n"
" <TO>8549672167</TO>\n"
" <FROM>8936742582</FROM>\n"
" <TIME>5/10/2009 19:49:3</TIME><TEXT>Blah Blah Blah</TEXT>\n"
"</ROW>\n"
"<ROW num=\"382\">\n"
" <TO>85496741267</TO>\n"
" <FROM>8591903412</FROM>\n"
" <TIME>5/10/2009 19:49:37</TIME>\n"
" <TEXT>Hme</TEXT>\n"
"</ROW>\n"
"<ROW num=\"381\">\n"
" <TO>8549672167412</TO>\n"
" <FROM>8936742582</FROM>\n"
" <TIME>5/10/2009 19:49:3</TIME><TEXT>Blah Blah Blah</TEXT>\n"
"</ROW>")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html