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>Use <code>pattern.search()</code> instead of <code>pattern.match()</code>.</p>

<p><code>pattern.match()</code> always matches from the start of the string (which includes the PREFIX).
<code>pattern.search()</code> searches anywhere within the string.</p>

python regex