import re
regex = re.compile(r"^1?(0*11+)*0*1?$", flags=re.MULTILINE)
test_str = ("accepts:\n"
"001\n"
"0\n\n"
"1\n"
"1110011\n"
"100110\n"
"001100\n"
"rejects:\n"
"010\n"
"111010\n"
"01000000")
subst = "$1$2$3"
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