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
Mark Fanty wrote:
In perl, I might do (made up example just to illustrate the point):
if(/add (\d+) (\d+)/) {
do_add($1, $2);
} elsif (/mult (\d+) (\d+)/) {
do_mult($1,$2);
} elsif(/help (\w+)/) {
show_help($1);
}
or even
do_add($1,$2) if /add (\d+) (\d+)/;
do_mult($1,$2) if /mult (\d+) (\d+)
Steven Bethard <[EMAIL PROTECTED]> wrote:
> I get a bit uneasy from the repeated calls to m.group... If I was going
> to build a class around the re, I think I might lean towards something like:
>
> class ReWithMemory(object):
> def search(self, are, aline):
> self.mo = re.search(a
Alex Martelli wrote:
class ReWithMemory(object):
def search(self, are, aline):
self.mo = re.search(are, aline)
return self.mo
def group(self, n):
return self.mo.group(n)
m = ReWithMemory()
if m.search(r'add (\d+) (\d+)', line):
do_add(m.group(1), m.group(2))
elif
Mark Fanty wrote:
> No nesting, but the while is misleading since I'm not looping and this
> is a bit awkward. I don't mind a few more key strokes, but I'd like
> clarity. I wish I could do
>
> if m = re.search(r'add (\d+) (\d+)', $line):
> do_add(m.group(1), m.group(2))
> elif m = re.sear
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> 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))
> e
Mark Fanty <[EMAIL PROTECTED]> wrote:
> In perl, I might do (made up example just to illustrate the point):
>
> if(/add (\d+) (\d+)/) {
>do_add($1, $2);
> } elsif (/mult (\d+) (\d+)/) {
>do_mult($1,$2);
> } elsif(/help (\w+)/) {
>show_help($1);
> }
There was a thread about this r
what about something like this?
>>> import re
>>> m = re.match(r"""(?Padd|mult) (?P\d+)
(?P\d+)""", 'add 3 5')
>>> from operator import add, mul
>>> op = {'add': add, 'mult: mul}
>>> op[m.groupdict()['operator']](int(m.groupdict()['int_1']),
int(m.groupdict()['int_2']))
8
--
http://mail.python.or
In perl, I might do (made up example just to illustrate the point):
if(/add (\d+) (\d+)/) {
do_add($1, $2);
} elsif (/mult (\d+) (\d+)/) {
do_mult($1,$2);
} elsif(/help (\w+)/) {
show_help($1);
}
or even
do_add($1,$2) if /add (\d+) (\d+)/;
do_mult($1,$2) if /mult (\d+) (\d+)/;
show_help($1