import re
regex = re.compile(r"(?::|^)((?:0+:){2,}0+)(?=:|$)|(?::|^)(0+)([0-9a-f]+)(?=:|$)|\b0+([0-9a-f]{1,4})\b", flags=re.IGNORECASE)
test_str = ("2001:0db8:abcd:0012:0000:0000:0000:0001\n"
"2001:0db8:abcd:0012:0000:0000:0000:00a2\n"
"2001:0db8:abcd:0012:0000:0000:0000:00ff\n"
"a:b:0:c:d:e:f:g\n"
"2001:0db8:abcd:0012:0000:0000:0000:0001\n"
":00ff:0000:\n"
"0012:0000:0000:0000:0001")
subst = "${1:+::}${3}${4}"
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