How to get the "longest possible" match with Python's RE module?

MonkeeSage MonkeeSage at gmail.com
Tue Sep 12 08:18:46 CEST 2006


Or mabye something like this is better:

def matcher(string, pattern):
  out = ''
  for match in re.findall(r'\S*%s\S*' % pattern, string):
    if (len(match) >= len(out)):
      out = match
  return out

p1 = 'dodad donkeykong dolittle dodaday'
p2 = 'oneself self-serving selfsufficient oneselfsufficient'
print matcher(p1, 'do')
# donkeykong
print matcher(p2, 'self')
# oneselfsufficient




More information about the Python-list mailing list