title: Python Regular Expression with optional but greedy groups
body: <p>I'm trying to write a regular expression to match a string that may or may not contain two tags. I need the expression to return me all five elements of the string, depending on whether they exist, but when I make the tags optional, the wildcard bits seem to gobble them up:</p>
  
  <p>Inputs could be:</p>
  
  <pre><code>text{a}more{b}words  
  {a}text{b}test  
  text  
  text{b}text  
  text{b}  
  text{a}text 
  </code></pre>
  
  <p>Et cetera. The only thing guaranteed is that <code>&lt;a&gt;</code> will always be before <code>&lt;b&gt;</code>, provided they exist.</p>
  
  <p>My expression now looks as follows:</p>
  
  <pre><code>^(.*?)(\{a\})?(.*?)(\{b\})?(.*?)$
  </code></pre>
  
  <p>Unfortunately, this ends up throwing all text into the last group, regardless of whether or not the tags are present. Is there some way to make them greedy, yet keep them optional? <code>re.findall</code> doesn't seem to help either unfortunately.</p>
  
  <p>Any help would be greatly appreciated! :)</p>