On Tue, Mar 16, 2010 at 12:45 AM, samb <sam.ban...@gmail.com> wrote: > Hi, > > I'm trying to do something like : > > if m = re.match(r'define\s+(\S+)\s*{$', line): > thing = m.group(1) > elif m = re.match(r'include\s+(\S+)$', line): > thing = m.group(1) > else > thing = "" > > But in fact I'm not allowed to affect a variable in "if" statement. > My code should then look like : > > if re.match(r'define\s+(\S+)\s*{$', line): > m = re.match(r'define\s+(\S+)\s*{$', line) > thing = m.group(1) > elif re.match(r'include\s+(\S+)$', line): > m = re.match(r'include\s+(\S+)$', line) > thing = m.group(1) > else > thing = "" > > Which is not nice because I'm doing twice the same instruction > or like : > > m = re.match(r'define\s+(\S+)\s*{$', line) > if m: > thing = m.group(1) > else: > m = re.match(r'include\s+(\S+)$', line) > if m: > thing = m.group(1) > else > thing = "" > > Which isn't nice neither because I'm going to have maybe 20 match > tests and I wouldn't like to have 20 indentations. > > Anyone a recommendation?
def extract_thing(line): for regex in (r'define\s+(\S+)\s*{$', r'include\s+(\S+)$'): m = re.match(regex, line) if m: return m.group(1) return "" Or if the real code is more complicated than your example: def extract_thing(line): m = re.match(r'define\s+(\S+)\s*{$', line) if m: return m.group(1) m = re.match(r'include\s+(\S+)$', line) if m: return m.group(1) #etc... return "" Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list