[Tutor] search list with regex

Steven D'Aprano steve at pearwood.info
Tue Feb 1 00:22:35 CET 2011


Elwin Estle wrote:

> Tcl's list search command has the option to search for a list element
> that matches a given regex.  Is there something similar in python?

Not using regexes.

> If not, it seems like it should be fairly trivial for me to write my
> own (just wondering if I would be re-inventing the wheel).

If all you want to do is match an exact string, then lists already have 
this:

 >>> ['fe', 'fi', 'fo', 'fum'].index('fo')
2

If you want to match the start of the item:

def find_prefix(alist, prefix):
     for i, item in enumerate(alist):
         if item.startswith(prefix):
             return i
     raise ValueError('not found')

Or match a substring:

def find_substring(alist, substr):
     for i, item in enumerate(alist):
         if substr in item:
             return i
     raise ValueError('not found')

If all you want is *exact* matches, these will be much faster than a 
regex solution. If you want case-insensitive exact matches:

def find_exact(alist, target, insensitive=False):
     if insensitive:
         return alist.index(target)
     target = target.lower()
     for i, item in enumerate(alist):
         if item.lower() == target:
             return i
     raise ValueError('not found')


To match with a regex, something like this should work:

import re
def find_re(alist, prefix):
     for i, item in enumerate(alist):
         if re.search(prefix, item):
             return i
     raise ValueError('not found')

or use re.match to match a prefix instead.




-- 
Steven



More information about the Tutor mailing list