Python - Filename validation help needed
<p>Bad Filename Example:   <code>foo is-not_bar-3.mp4</code>
What it should be: <code>foo_is_not_bar-3.mp4</code></p>

<p>I only want to keep a <code>-</code> for the last bit of the string if it is a digit followed by the extension. The closest I have gotten thus far is with the following code:</p>

<pre><code>fname = 'foo is-not_bar-3.mp4'
valchars = '-_. %s%s' % (string.ascii_letters, string.digits)
f = ''.join(c for c in fname if c in valchars).replace(' ', '_').replace('-', '_')
</code></pre>

<p>You can use regex replacement with a negative lookahead:</p>

<pre><code>import re

fname = 'foo is-not_bar-3.mp4'
f = re.sub(r'\s|-(?!\d+)', '_', fname)
print(f)
&gt;&gt; 'foo_is_not_bar-3.mp4'
</code></pre>

<p>This will replace every <code>-</code> and space with <code>_</code> <strong>unless</strong> it is followed by a number.</p>

python