import re
regex = re.compile(r"art(?:(?!art-)[\s\S])*code:\"XXX\"(?:(?!art-)[\s\S])*art-", flags=re.MULTILINE)
test_str = ("begin\n"
"more text \n"
"art\n"
" id:213213\n"
" code:\"XXX\"\n"
" name:234\n"
"art-\n"
"art\n"
" id:543\n"
" name:72\n"
" code:\"AAA\"\n"
"art-\n"
"art\n"
" code:\"XXX\"\n"
" id:32\n"
" name:46\n"
"art-\n"
"art\n"
" code:\"CCC\"\n"
" id:8765\n"
"art-\n"
"art\n"
" id:876\n"
" code:\"DDD\"\n"
"art-\n"
"even more text\n"
"even more text\n"
"end")
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