Python regex numbers and underscores
<p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>

<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>

<p>For example</p>

<pre><code>FOO_2016_03_23.dat
</code></pre>

<p>Can't seem to get the right regex.  I've tried the following:</p>

<pre><code>pattern = re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')
&gt;&gt;&gt; []

pattern = re.compile(r'*(\d{4})_(\d{2})_(\d{2}).dat')
&gt;&gt;&gt; sre_constants.error: nothing to repeat
</code></pre>

<p>Regex is certainly a weakpoint for me.  Can anyone explain where I'm going wrong?</p>

<p>To get the files, I'm doing:</p>

<pre><code>files = [f for f in os.listdir(directory) if pattern.match(f)] 
</code></pre>

<p>PS, how would I allow for .dat and .DAT (case insensitive file extension)?</p>

<p>Thanks</p>

<p>You have two issues with your expression:
<code>re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')</code></p>

<p>The first one, as a previous comment stated, is that the <code>.</code> right before <code>dat</code> should be escaped by putting a backslash (<code>\</code>) before. Otherwise, python will treat it as a special character, because in regex <code>.</code> represents "any character".</p>

<p>Besides that, you're not handling uppercase exceptions on your expression. You should make a group for this with <code>dat</code> and <code>DAT</code> as possible choices.</p>

<p>With both changes made, it should look like:</p>

<p><code>re.compile(r'(\d{4})_(\d{2})_(\d{2})\.(?:dat|DAT)')</code></p>

<p>As an extra note, I added <code>?:</code> at the beginning of the group so the regex matcher ignores it at the results.</p>

python regex