title: Alternative to the `match = re.match(); if match: ...` idiom?
body: <p>If you want to check if something matches a regex, if so, print the first group, you do..</p>
  
  <pre><code>import re
  match = re.match("(\d+)g", "123g")
  if match is not None:
      print match.group(1)
  </code></pre>
  
  <p>This is completely pedantic, but the intermediate <code>match</code> variable is a bit annoying..</p>
  
  <p>Languages like Perl do this by creating new <code>$1</code>..<code>$9</code> variables for match groups, like..</p>
  
  <pre><code>if($blah ~= /(\d+)g/){
      print $1
  }
  </code></pre>
  
  <p>From <a href="http://www.reddit.com/r/Python/comments/92ewt/experiment_adding_re_to_python_string_objects/c0b7895" rel="noreferrer">this reddit comment</a>,</p>
  
  <pre><code>with re_context.match('^blah', s) as match:
      if match:
          ...
      else:
          ...
  </code></pre>
  
  <p>..which I thought was an interesting idea, so I wrote a simple implementation of it:</p>
  
  <pre><code>#!/usr/bin/env python2.6
  import re
  
  class SRE_Match_Wrapper:
      def __init__(self, match):
          self.match = match
  
      def __exit__(self, type, value, tb):
          pass
  
      def __enter__(self):
          return self.match
  
      def __getattr__(self, name):
          if name == "__exit__":
              return self.__exit__
          elif name == "__enter__":
              return self.__name__
          else:
              return getattr(self.match, name)
  
  def rematch(pattern, inp):
      matcher = re.compile(pattern)
      x = SRE_Match_Wrapper(matcher.match(inp))
      return x
      return match
  
  if __name__ == '__main__':
      # Example:
      with rematch("(\d+)g", "123g") as m:
          if m:
              print(m.group(1))
  
      with rematch("(\d+)g", "123") as m:
          if m:
              print(m.group(1))
  </code></pre>
  
  <p>(This functionality could theoretically be patched into the <code>_sre.SRE_Match</code> object)</p>
  
  <p>It would be nice if you could skip the execution of the <code>with</code> statement's code block, if there was no match, which would simplify this to..</p>
  
  <pre><code>with rematch("(\d+)g", "123") as m:
      print(m.group(1)) # only executed if the match occurred
  </code></pre>
  
  <p>..but this seems impossible based of what I can deduce from <a href="http://www.python.org/dev/peps/pep-0343/" rel="noreferrer">PEP 343</a></p>
  
  <p>Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..</p>