What Is This?
This regex pattern extracts the file extension from a filename or path. It matches a dot followed by one or more word characters at the end of a string. The extension is captured in group 1 for easy extraction. For example, from 'document.pdf' it captures 'pdf'.
How to Use
The Pattern
Use this pattern to extract file extensions for file type checking, routing, or content-type detection. The captured group 1 contains the extension without the dot. Be aware that some files have multiple extensions (.tar.gz) or no extension at all.
/\.(\w+)$/
Examples
Common extensions
Matches: document.pdf image.jpg script.js styles.css archive.tar.gz Does not match: README Makefile .gitignore file
Path handling
Matches: /path/to/file.html C:\Users\file.docx ~/config.json Does not match: file. noextension file.
Related Entries
More from this reference:
Frequently Asked Questions
Does this work for files with multiple extensions?
This pattern captures only the last extension (e.g., 'gz' from 'archive.tar.gz'). To capture all extensions, use \.([\w.]+)$ or a different approach. For most use cases, the last extension is sufficient.
How do I handle hidden files (like .gitignore)?
Hidden files without a base name (starting with a dot) are edge cases. The pattern would match 'gitignore' as the extension of '.gitignore'. For these cases, check if the filename itself is just an extension.