import re
regex = re.compile(r"^(?:GET|HEAD):.*?application\/(?:activity|ld)\+json", flags=re.MULTILINE)
test_str = ("======================================================\n"
"Basic testing with \"just\" the expexted pattern\n"
"======================================================\n\n"
"GET:application/activity+json\n"
"GET:application/activity+xml\n"
"HEAD:application/activity+json\n"
"POST:application/activity+json\n\n"
"GET:application/ld+json\n"
"GET:application/ld+xml\n"
"HEAD:application/ld+json\n"
"POST:application/ld+json\n\n"
"======================================================\n"
"Testing with additional suffix in the header\n"
"======================================================\n\n"
"GET:application/activity+json,something,else\n"
"GET:application/activity+xml,something,else\n"
"HEAD:application/activity+json,something,else\n"
"POST:application/activity+json,something,else\n\n"
"GET:application/ld+json,something,else\n"
"GET:application/ld+xml,something,else\n"
"HEAD:application/ld+json,something,else\n"
"POST:application/ld+json,something,else\n\n"
"======================================================\n"
"Testing with additional prefix *and* suffix in the header\n"
"======================================================\n\n"
"GET:something before, application/activity+json, something, after\n"
"GET:something before, application/activity+xml, something, after\n"
"HEAD:something before, application/activity+json, something, after\n"
"POST:something before, application/activity+json, something, after\n\n"
"GET:something before, application/ld+json, something, after\n"
"GET:something before, application/ld+xml, something, after\n"
"HEAD:something before, application/ld+json, something, after\n"
"POST:something before, application/ld+json, something, after")
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