import re
regex = re.compile(r"(?P<field>^[\w-]+): *(?P<value>[\s\S]+?)(?=^[\w-]+: *|\Z)", flags=re.MULTILINE)
test_str = ("Message-ID: <1608636066635.7f830.79689714@crcvmail15.nm>\n"
"Received: from 125.209.x.x (net58.219.x-x.host.lt-nn.net [91.219.x.x])\n"
" by crcvmail15.google.com with ESMTP id +844Q-zuS122aEqk5CZDZg\n"
" for <test@google.com>;\n"
"Received: from 125.209.x.x (net58.219.x-18.host.lt-nn.net [91.219.x.x])\n"
" by crcvmail15.google.com with ESMTP id +844Q-zuS122aEqk5CZDZg\n"
" for <test@google.com>;\n"
" Tue, 22 Dec 2020 11:20:58 -0000\n"
"From: \"test\"<from@google.com>\n"
"To: test@google.com\n"
"Subject:example email\n"
"Content-Type: text/html; charset=\"utf-8\"\n"
"Content-Transfer-Encoding: quoted-printable")
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