import re
regex = re.compile(r"^M{0,4}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$", flags=re.MULTILINE)
test_str = ("I\n"
"II\n"
"III\n"
"IV\n"
"V\n"
"VI\n"
"VII\n"
"VIII\n"
"IX\n"
"X\n"
"XI\n"
"XII\n"
"XIII\n"
"XIV\n"
"XV\n"
"XVI\n"
"XVII\n"
"XVIII\n"
"XIX\n"
"XX\n"
"XLIV\n"
"XLIX\n"
"LXXIX\n"
"XCIV\n"
"XCIX\n"
"C\n"
"CI\n"
"CII\n"
"CIII\n"
"CIV\n"
"CVI\n"
"CIX\n"
"CD\n"
"CM\n"
"CC\n"
"CCC\n"
"D\n"
"DC\n"
"DCC\n"
"DCCC\n"
"CX\n"
"CXX\n"
"CXIX\n"
"CMXCIX\n"
"MCMXLIV\n"
"MMMMCCCXII\n")
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