affectation in if statement

Rob Williscroft rtw at rtw.me.uk
Tue Mar 16 04:52:45 EDT 2010


samb wrote in news:5c361012-1f7b-487f-915b-0f564b238be3
@e1g2000yqh.googlegroups.com in comp.lang.python:

> Thanks for all those suggestions.
> They are good!
> 
> 1) Let's suppose now that instead of just affecting "thing =
> m.group(1)", I need to do a piece of logic depending on which match I
> entered...
> 
> 2) Concerning the suggestion :
> m = re.match(r'define\s+(\S+)\s*{$', line)
> if m:
>     thing = m.group(1)
> 
> m = re.match(r'include\s+(\S+)$', line)
> if m:
>     thing = m.group(1)
> 
> #etc...
> 
> It means that I'll do all the checks, even if the first one did match
> and I know that the next will not...
> 

Ths is how I did it when I had the need:

class ReMatch( object ):
  def __call__( self, pat, string ):
    import re
    self.match = re.match( pat, string )
    return self.match is not None

clip = ...

re = ReMatch()

if re( r'\s*TM(\d+)', clip ):
  ...    	
elif re( r'\s*(https?://.*)', clip ):
   ...
elif re( r'\d{12}$', clip ):
  ...

Rob.
-- 



More information about the Python-list mailing list