Search code examples
python-3.xpython-re

How does one match the file extension using re in python?


I would like to match any file with .Mp4 extension. The code does not seem to work as I thought...Any leads??

import re

ext=r"\.Mp4$"
files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]


for f in files:
    if re.match(ext, f): 
        print(f)
    else:
        pass

Solution

  • I can see is that you are using re.match() which only checks the beginning of the string for matches regardless of the '$' flag you were passing. See https://docs.python.org/3/library/re.html#search-vs-match for more info on search vs match.

    Changing your code to search returns the expected results:

    import re
    
    ext=r"\.mp4$"
    files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]
    
    
    for f in files:
        if re.search(ext, f, flags=re.I): 
            print(f)
        else:
            pass