best way to do a series of regexp checks with groups

Alex Martelli aleaxit at
Mon Jan 24 03:38:25 EST 2005

Nick Craig-Wood <nick at> wrote:

> Here is a different solution...
> class Result:
>     def set(self, value):
>         self.value = value
>         return value
> m = Result()
> if m.set('add (\d+) (\d+)', line)):
>     do_add(,
> elif m.set('mult (\d+) (\d+)', line)):
>     do_mult(,
> elif m.set('help (\w+)', line)):
>     show_help(

This is roughly the same as my Cookbook recipe for test-and-set, but if
all you're using it for is RE search and MO access you might be better
off giving more responsibilities to your auxiliary class, such as:

class ReWithMemory(object):
    def search(self, are, aline): =, aline)
    def group(self, n):

m = ReWithMemory()

if'add (\d+) (\d+)', line):
elif'mult (\d+) (\d+)', line):
elif'help (\w+)', line):

Demeter's Law suggests that the '' accesses in your
approach are better handled by having m delegate to its `value'; and the
repeated m.set( ... seem to be a slight code smell, violating
"once and only once", which suggests merging into a single `set' method.
Your approach is more general, of course.


More information about the Python-list mailing list