import re
regex = re.compile(r"\s*(?:.*?[:=;]|ORCPT|for|domain of|ESMTPSA id)?\s*(?:\"?([\w ]*?)[ \"<])?\s*<?([\w.]*?@[\w.]*)>?", flags=re.IGNORECASE)
test_str = ("John Smith <john.smith@gmail.com>\n"
"John Smith <johnsmith@gmail.com>\n"
"\"John Smith\" <johnsmith@gmail.com>\n"
"\"John\" <johnsmith@gmail.com>\n"
"John Smith<johnsmith@gmail.com>\n"
"<johnsmith@gmail.com>\n"
"johnsmith@gmail.com\n"
"mailto:johnsmith@gmail.com\n"
"\"John\"<johnsmith@gmail.com>\n\n"
"To: John Smith <john.smith@gmail.com>\n"
"From: John Smith <john.smith@gmail.com>\n"
"Reply-to: john.smith@gmail.com\n"
"Return-path: <john.smith@gmail.com>\n"
"Message-id: <john.smith@gmail.com>\n"
"References: <john.smith@gmail.com>\n"
"Original-recipient: rfc822;john.smith@gmail.com\n"
"for john.smith@gmail.com\n"
"ESMTPSA id <john.smith@gmail.com>\n"
"domain of john.smith@gmail.com\n"
"envelope-from=john.smith@gmail.com\n"
"(ORCPT john.smith@gmail.com)")
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