[Tutor] search list with regex

Wayne Werner waynejwerner at gmail.com
Mon Jan 31 16:20:23 CET 2011


On Mon, Jan 31, 2011 at 7:07 AM, Elwin Estle <chrysalis_reborn at yahoo.com>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?  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).


matching_items = []
for item in yourlist:
    result = re.search('[sS]ome expression', item) # and of course
s/search/match, if you're interested in matching
    if result:
        matching_items.append(item)

Or you could go for more terse syntax via list comp:

matching_items = [item for item in yourlist if re.search('contains', item)]

Or if you want one at a time you could change [] for () and turn it into a
generator expression.

However, the list itself doesn't have any method for matching. Here are its
"public" methods:

append
count
extend
index
insert
pop
remove
reverse
sort

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110131/635cc032/attachment.html>


More information about the Tutor mailing list