Python - Filename validation help needed
Question: Bad Filename Example: `foo is-not_bar-3.mp4` What it should be:
`foo_is_not_bar-3.mp4`

I only want to keep a `-` 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:

    
    
    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('-', '_')
    


Answer: You can use regex replacement with a negative lookahead:

    
    
    import re
    
    fname = 'foo is-not_bar-3.mp4'
    f = re.sub(r'\s|-(?!\d+)', '_', fname)
    print(f)
    >> 'foo_is_not_bar-3.mp4'
    

This will replace every `-` and space with `_` **unless** it is followed by a
number.

