checking a string against multiple patterns

Hrvoje Niksic hniksic at xemacs.org
Tue Dec 18 11:35:49 EST 2007


tomasz <tmkmarc at googlemail.com> writes:

> here is a piece of pseudo-code (taken from Ruby) that illustrates the
> problem I'd like to solve in Python:
[...]

I asked the very same question in
http://groups.google.com/group/comp.lang.python/browse_frm/thread/3e8da954ff2265e/4deb5631ade8b393
It seems that people either write more elaborate constructs or learn
to tolerate the nesting.

> Is there an alternative to it?

A simple workaround is to write a trivial function that returns a
boolean, and also stores the match object in either a global storage
or an object.  It's not really elegant, especially in smaller scripts,
but it works:

def search(pattern, s, store):
    match = re.search(pattern, s)
    store.match = match
    return match is not None

class MatchStore(object):
    pass   # irrelevant, any object with a 'match' attr would do

where = MatchStore()
if search(pattern1, s, where):
    pattern1 matched, matchobj in where.match
elif search(pattern2, s, where):
    pattern2 matched, matchobj in where.match
...



More information about the Python-list mailing list