Learn how to validate file extensions using regex patterns. This comprehensive guide covers common files like documents, spreadsheets, presentations, images, audio, video, archives, etc. Regular expre...
Learn how to validate file extensions using regex patterns. This comprehensive guide covers common files like documents, spreadsheets, presentations, images, audio, video, archives, etc. Regular expressions are more powerful than os and pathlib for checking file extensions.
To check the file extension using regex, we need to define a pattern that matches the file extension. The \w+ expression matches one or more word characters. We can use the search() function of the re module to match the pattern against the file path. If matched, we extract the file extension from the group(1) method of the match object.
Matching the file extension is nontrivial for all situations. A simple, elegant solution recognizes a file name with extension based on regular expression. I changed the pattern to match the extension with a non-grouping parentheses (?:…). The grouping parentheses delimit the pattern that recognizes the extension \.[^.]*$.
You need to test it out to ensure it works correctly as the original intent was to validate file paths and extensions. I added A-Z to the pattern but changing the string to lowercase would probably suffice. It handles spaces in folders and file names. Also handles multiple dots in file name.