best way to do a series of regexp checks with groups
Mark Fanty
markfanty at yahoo.com
Mon Jan 24 22:24:43 EST 2005
This is the kind of thing I meant. I think I have to get used to writing
small, light-weight classes. You inspired this variation which is a little
more verbose in the class definition, but less so in the use:
class Matcher:
def search(self, r,s):
self.value = re.search(r,s)
return self.value
def __getitem__(self, i):
return self.value.group(i)
m = Matcher()
if m.search(r'add (\d+) (\d+)', line):
do_add(m[1], m[2])
elif m.search(r'mult (\d+) (\d+)', line):
do_mult(m[1], m[2])
elif m.search(r'help (\w+)', line):
show_help(m[1])
As for using regular expressions too much... they are why I've liked perl so
much for quick file processing for years. I don't like perl objects at all,
which is why I'm trying python, but the re package has not been my favorite
so far...
"Nick Craig-Wood" <nick at craig-wood.com> wrote in message
news:slrncv8ar0.m68.nick at irishsea.home.craig-wood.com...
>
> There was a thread about this recently under the title
>
> "regular expression: perl ==> python"
>
> Here is a different solution...
>
> class Result:
> def set(self, value):
> self.value = value
> return value
>
> m = Result()
>
> if m.set(re.search(r'add (\d+) (\d+)', line)):
> do_add(m.value.group(1), m.value.group(2))
> elif m.set(re.search(r'mult (\d+) (\d+)', line)):
> do_mult(m.value.group(1), m.value.group(2))
> elif m.set(re.search(r'help (\w+)', line)):
> show_help(m.value.group(1))
>
> --
> Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list