Python exceptions and regex
Question: I have an expression which I'm using to raise exceptions in the code, except
one case where this expression is allowed:

    
    
    searchexp = re.search( r'^exp1=.*, exp2=(.*),.*', line )
    

I want to raise an exception whenever this condition is hit except one case
when I want it to print a warning

    
    
    elif searchexp: 
      if searchexp.group(1) == 'tag'): 
        print("-w- just a warning that its a tag")
      else:
        raise Exception("-E- This is illegal to do")
    

In simple English

    
    
    if (searchexp)
      raise an Exception except if searchexp.group(1) == 'tag'
    

How do I do this in python?


Answer: You can do it this way. Wrap every `re.search()` with `wrap_search()`. Which
will check the returned match.

    
    
    import warnings
    
    def wrap_search(match):
        if not match:
            return
    
        if match.group(1) == "tag":
            warnings.warn("-w- just a warning that its a tag")
        else:
            raise Exception("-E- This is illegal to do")
    
        return match
    
    searchexp = wrap_search(re.search( r'^exp1=.*, exp2=(.*),.*', line ))
    

