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>Does this do what you want?</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; pattern = r'\A[a-z]+_\d{4}_\d{2}_\d{2}\.dat\Z'
&gt;&gt;&gt; string = 'FOO_2016_03_23.dat'
&gt;&gt;&gt; re.search(pattern, string, re.IGNORECASE)
&lt;_sre.SRE_Match object; span=(0, 18), match='FOO_2016_03_23.dat'&gt;
&gt;&gt;&gt; 
</code></pre>

<p>It appears to match the format of the string you gave as an example.</p>

python regex