On May 21, 10:38 am, [EMAIL PROTECTED] wrote: > Hello, > > I have an if-elif chain in which I'd like to match a string against > several regular expressions. Also I'd like to use the match groups > within the respective elif... block. The C-like idiom that I would > like to use is this: > > if (match = my_re1.match(line): > # use match > elsif (match = my_re2.match(line)): > # use match > elsif (match = my_re3.match(line)) > # use match > > ...buy this is illegal in python. The other way is to open up an else: > block in each level, do the assignment and then the test. This > unneccessarily leads to deeper and deeper nesting levels which I find > ugly. Just as ugly as first testing against the RE in the elif: clause > and then, if it matches, to re-evaluate the RE to access the match > groups. > > Thanks, > robert
You could use named groups to search for all three patterns at once like this: original: prog1 = re.compile(r'pat1') prog2 = re.compile(r'pat2') prog3 = re.compile(r'pat3') ... Becomes: prog = re.compile(r'(?P<p1>pat1)|(?P<p2>pat2)|(?P<p3>pat3)') match = prog.match(line) for p in 'p1 p2 p3'.split(): if match.groupdict()[p]: do_something_for_prog(p) - Paddy. -- http://mail.python.org/mailman/listinfo/python-list