Question

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?

Was it helpful?

Solution

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']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top