Python – finding the longest sequence with findall

Python – finding the longest sequence with findall

found = re.findall("g+", "fggfggggfggfg", re.DOTALL)

I’d like to find a longest matches for a pattern using findall. I’ve found some solutions but only for re.match or re.finditer. Could anybody give me an advice please?

re.DOTALL does nothing in this case so I’ve just taken it out for simplicity’s sake:

>>> import re
>>> max(re.findall("g+", "fggfggggfggfg"), key=len)
'gggg'

If you need all of them in order of length:

>>> sorted(re.findall("g+", "fggfggggfggfg"), key=len, reverse=True)
['gggg', 'gg', 'gg', 'g']
.
.
.
.