If you are not stuck in regexes, you can use itertools.groupby :
from itertools import groupby ip6 = "1234:0678:0000:0000:00cd:0000:0000:0000" longest = 0 for section, elems in groupby(ip6.split(':')): if section == '0000': longest = len(list(elems)) print longest
I am sure that this can be reduced to something more elegant, but I think it speaks to the point.
source share