title: Python: iterating by match to regex
body: <p>I am making a script to automatically parse some text data (with a complex structure) and insert it into a MySQL database.</p>
  
  <p>I would like to have multiple for loops that iterate over a list of files based on  regex matches to the file names. In the end I will concatenate them and insert them into the database.</p>
  
  <p>Here are my regex expressions:</p>
  
  <pre><code>Trgx= re.compile('([a-zA-Z0-9]{3,4})_.*_.*_.*$');
  Dtrgx= re.compile('[a-zA-Z0-9]{3,4}_[a-zA-Z0-9]{3,4}_([0-9]{10})_[0-9]{3}'); 
  Mrgx= re.compile('.*_([a-zA-Z0-9]{3,4})_.*$'); 
  Hrgx= re.compile('.*([0-9]{3}).csv$'); 
  </code></pre>
  
  <p>My filenames look like this:</p>
  
  <pre><code>ecd_cdd_2012102100_000.csv
  ecd_cdd_2012102100_024.csv
  ecd_hdd_2012102200_000.csv
  ecd_hdd_2012102200_024.csv
  ecd_hdd_2012102200_048.csv
  ecd_avgt_2012102200_120.csv
  ecd_avgt_2012102200_144.csv
  ecd_avgt_2012102200_168.csv
  ecd_mint_2012102200_192.csv
  ecd_maxt_2012102200_144.csv
  ecd_maxt_2012102200_168.csv
  ecd_cdd_2012102200_000.csv
  ecd_cdd_2012102200_024.csv
  </code></pre>
  
  <p>Each expression captures a subset of the file name:</p>
  
  <ul>
  <li><em>Trgx</em> captures the first part ("ecd" in every instance in this example)</li>
  <li><em>Mrgx</em> captures the second part ("cdd","hdd","avgt",etc)</li>
  <li><em>Dtrgx</em> captures the date/time segment (like 2012102100)</li>
  <li><em>Hrgx</em>  captures the last part (like 000 or 024, before the extension)</li>
  </ul>
  
  <p>Every file name will match every regular expression, but <code>.group(1)</code> will be populated 
  by different values. </p>
  
  <p>I want to iterate through the files using the regex exprssions as "grouping" elements, so that I concatenate them together in the right order.</p>
  
  <p>Something like this:</p>
  
  <pre><code>for fileName in fileNameList
      for each distinct value in  Trgx.group(1)
           for each distinct value in  Dtrgx.group(1)
                for each distinct value in Hrgx.group(1)
                       do whatever
  </code></pre>