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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With