import re
regex = re.compile(r"^(\+){0,1}(254){0,1}(70|71|72|79)(\d{7})|(254){0,3}(740|741|742|743|745|746|748|757|758|759|768|769|110|111)(\d{6})$", flags=re.MULTILINE)
test_str = ("VALID NUMBERS\n"
"254715228228\n"
"254722228228\n"
"254729228228\n"
"254745229228\n"
"254769229228\n"
"254110229228\n"
"254111229228\n\n"
"INVALID NUMBERS\n"
"254730229228\n"
"254744229228\n"
"254747229228\n"
"254760229228\n"
"254100229228\n\n\n"
"Sources: https://ca.go.ke/wp-content/uploads/2020/01/Telecommunication-Numbering-Plan-for-Kenya-Feb-2020-compressed.pdf\n\n\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