samb wrote:
Hi,

I've found a work around, inspired from Rob Williscroft :

class ReMatch(object):
    """
        Object to be called :
        1st time : do a regexp.match and return the answer (args:
regexp, line)
        2nd time : return the previous result (args: prev)
    """
    def __call__(self, regexp='', line='', prev=False):
        if prev:
            return self.prev_match
        self.prev_match = re.match(regexp, line)
        return self.prev_match

re_match = ReMatch()

if re_match(r'define\s+(\S+)\s*{$', line):
    m = re_match(prev=True)
    # do some logic with m
elif re_match(r'include\s+(\S+)$', line):
    m = re_match(prev=True)
    # do some logic with m
else
    # do some logic

Hope this is efficient ... I guess yes.

Cheers,
Sam
What do you mean by efficient ? If you're talking about speed, make sure you care about it before doing some optimization. If you talk about readability then it is absolutely *not* efficient (to my humble opinion).

define, include = re.match(r'define\s+(\S+)\s*{$', line), re.match(r'include\s+(\S+)$', line)
if define:
   # do some stuff
elif include:
   # do some other stuff
else:
   # hello world
If you then have some speed problem with that script, you'll start caring about how to execute if faster by making sure that only necessary calls to re.match are done.

match = re.match(r'(define)\s+(\S+)\s*{$', line) or re.match(r'(include)\s+(\S+)$', line) # note that the second operand is executed only if the first is None

if match.group(1) == 'define':
   # do some stuff with match.group(2)

elif match.group(1) == 'include':
   # do some other stuff with match.group(2)

else:
   # hello world


JM
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to