Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
Jakub Turcovsky Avatar asked Mar 24 '23 07:03

Jakub Turcovsky


1 Answers

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']
like image 154
jamylak Avatar answered Apr 05 '23 21:04

jamylak