import re
regex = re.compile(r"^([0-9]{3})-?([0-9]{3})-?([0-9]{3})-?([0-9]{3})?$", flags=re.MULTILINE)
test_str = ("009026405\n"
"01009556500\n"
"226-356-839\n"
"00829029200\n"
"008-018-454\n"
"009-513-213\n"
"00383951900\n"
"000147765000\n"
"96029000672\n"
"008-743-791\n"
"009568337\n"
"136759989000\n"
"009724967000\n"
"2RC0001624466\n"
"286169755000\n"
"201-947-430-0\n"
"241402504000\n"
"223651060000\n")
subst = "[$1.$2.$3.${4:+$4:000}]"
result = regex.sub(subst, test_str)
if result:
print(result)
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