title: Finding the last group in a regular expression
body: <p>Three underscore separated elements make my strings :
  - first (letters and digits)
  - middle (letters, digits and underscore)
  - last (letters and digits)</p>
  
  <p>The last element is optional.</p>
  
  <p>Note : I need to access my groups by their names, not their indices.</p>
  
  <p>Examples :</p>
  
  <pre><code>String : abc_def
  first : abc
  middle : def
  last : None
  </code></pre>
  
  <hr>
  
  <pre><code>String : abc_def_xyz
  first : abc
  middle: def
  last: xyz
  </code></pre>
  
  <hr>
  
  <pre><code>String : abc_def_ghi_jkl_xyz
  first : abc
  middle : def_ghi_jkl
  last : xyz
  </code></pre>
  
  <p>I can't find the right regex...</p>
  
  <p>I have two ideas so far :</p>
  
  <p><strong>Optional group</strong></p>
  
  <pre><code>(?P&lt;first&gt;[a-z]+)_(?P&lt;middle&gt;\w+)(_(?P&lt;last&gt;[a-z]+))?
  </code></pre>
  
  <p>But the middle group matches until the end of the string :</p>
  
  <pre><code>String : abc_def_ghi_jkl_xyz
  first : abc
  middle : def_ghi_jkl_xyz
  last : vide
  </code></pre>
  
  <p><strong>Using the '|'</strong></p>
  
  <pre><code>(?P&lt;first&gt;[a-z]+)_(?P&lt;middle&gt;\w+)_(?P&lt;last&gt;[a-z]+)|(?P&lt;first&gt;[a-z]+)_(?P&lt;middle&gt;\w+)
  </code></pre>
  
  <p>This expression is invalid : first and middle groups are declared two times. I though I could write an expression reusing the matched group from the first part of the expression :</p>
  
  <pre><code>(?P&lt;first&gt;[a-z]+)_(?P&lt;middle&gt;\w+)_(?P&lt;last&gt;[a-z]+)|(?P=first)_(?P=middle)
  </code></pre>
  
  <p>The expression is valid, however strings with just a first and a middle like abc_def are not matched.</p>
  
  <p><strong>Note</strong></p>
  
  <p>These strings are actually parts of a path I need to match. It could be paths like :</p>
  
  <ul>
  <li>/my/path/to/abc_def</li>
  <li>/my/path/to/abc_def/</li>
  <li>/my/path/to/abc_def/some/other/stuf</li>
  <li>/my/path/to/abc_def/some/other/stuf/</li>
  <li>/my/path/to/abc_def_ghi_jkl_xyz</li>
  <li>/my/path/to/abc_def_ghi_jkl_xyz/</li>
  <li>/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf</li>
  <li>/my/path/to/abc_def_ghi_jkl_xyz/some/other/stuf/</li>
  <li>...</li>
  </ul>
  
  <p>Any idea to solve my problem solely with regular expressions ? Post-processing the matched groups is not an option.</p>
  
  <p>Thank you very much !</p>