Skip to content

Regex for File Extension

This regex matches file extensions at the end of a string by capturing everything after the last dot. It uses the word character class (letters, digits, underscore) which covers virtually all standard file extensions. The pattern is commonly used in file upload validation, content type detection, and file system operations.

Pattern
\.(\w+)$
Test this pattern in the Regex Tester →

What is the regex pattern for File Extension?

The regex pattern for File Extension is \.(\w+)$. This regex matches file extensions at the end of a string by capturing everything after the last dot. It uses the word character class (letters, digits, underscore) which covers virtually all standard file extensions. The pattern is commonly used in file upload validation, content type detection, and file system operations. This pattern is commonly used for file upload validation and content type detection.

Test Examples

Match
document.pdf
Matches: .pdf
Match
archive.tar.gz
Matches: .gz
No Match
noextension

Common Uses

Variations

Specific extensions

\.(jpg|jpeg|png|gif|svg|webp)$

Only matches image file extensions

Double extensions

\.(\w+\.\w+)$

Matches compound extensions like .tar.gz

Case insensitive

\.(\w+)$

Add the 'i' flag for case-insensitive matching

Frequently Asked Questions

Does this match files with multiple extensions?

It matches only the last extension. For a file like archive.tar.gz, it captures .gz. Use the 'Double extensions' variation to capture .tar.gz as a compound extension.

Should I use regex for file type validation?

Regex on the extension is a quick first check, but file extensions can be changed. For security-sensitive uploads, also check the file's MIME type and magic bytes to verify the actual file content.

Why use \w+ instead of listing specific extensions?

Using \w+ makes the pattern generic and future-proof. If you need to restrict to specific file types, use the 'Specific extensions' variation with an explicit list of allowed extensions.

Related Patterns

URL Slug

^[a-z0-9]+(?:-[a-z0-9]+)*$

URL

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]...

Domain Name

^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-z...

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →