import re
regex = re.compile(r"^((?|[1-9](?=.*1\t+(?<x>0+))|[1-9]\d(?=.*2\t+(?<x>0+))|[1-9]\d{2}(?=.*3\t+(?<x>0+))|[1-9]\d{3}(?=.*4\t+(?<x>0+))|[1-9]\d{4}(?=.*5\t+(?<x>0+))|[1-9]\d{5}(?=.*6\t+(?<x>0+))|[1-9]\d{6}(?=.*7\t+(?<x>0+))|[1-9]\d{7}(?=.*8\t+(?<x>0+))))\b", flags=re.DOTALL | re.MULTILINE)
test_str = ("1\n"
"12\n"
"123\n"
"12345678\n"
"123456789\n\n"
"1 00000000\n"
"2 0000000\n"
"3 000000\n"
"4 00000\n"
"5 0000\n"
"6 000\n"
"7 00\n"
"8 0")
subst = "${x}$1"
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