import re
regex = re.compile(r"^(-?)P(?=.)((\d*)Y)?((\d+)M)?((\d*)D)?(T(?=\d)(\d+H)?(([\d]+)M)?(([\d]+(?:\.\d+))S)?)?$", flags=re.MULTILINE)
test_str = ("P2Y6M5DT12H35M30S\n"
"P1DT2H\n"
"P20M\n"
"PT20M\n"
"P0Y20M0D\n"
"P0Y\n"
"-P60D\n"
"PT1M30.5S\n"
"--\n"
"P-20M\n"
"P20MT\n"
"P1YM5D\n"
"P15.5Y\n"
"P1D2H\n"
"1Y2M\n"
"P2M1Y\n"
"P\n"
"PT15.S")
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