Skip to content

Regex for File Extension — Pattern, Examples & Caveats

Pattern
\.([A-Za-z0-9]+)$

This pattern captures the final file extension from a filename or path: a dot followed by alphanumeric characters at the end of the string. It is used to determine file type from a name. Extraction patterns pull substrings out of larger text rather than judging the whole input. They usually omit anchors and use the global flag to find every occurrence, often with capturing groups to isolate the part you want. Typical uses are scraping emails, URLs, tags or mentions from prose, logs and documents, where the surrounding text is irrelevant noise. It needs no special flags. Apply it across text to collect every occurrence. For compound extensions like .tar.gz it captures only gz; handle known compound cases explicitly if needed. It matches dotfiles' trailing part oddly and rejects names ending with a dot; validate real filenames separately. Extension is not a reliable indicator of actual content type — inspect bytes or MIME type for security-sensitive decisions. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • \. — a literal dot before the extension
  • ([A-Za-z0-9]+) — capture the extension characters
  • $ — end of string, ensuring it is the final extension

What it matches

photo.jpgarchive.tar.gzdocument.pdfscript.min.js

What it does not match

noextensionfile..hiddenpath/to/dir

When to use it

Reach for an extraction pattern when you need to pull structured tokens out of unstructured text: scraping contact details from a page, collecting links from a log, or harvesting tags from social content. Use capturing groups to isolate the part you want and the global flag to gather every occurrence. Clean the results afterward — extraction often grabs trailing punctuation or partial matches, so trim and deduplicate before storing or displaying the collected values.

Caveats

  • For compound extensions like .tar.gz it captures only gz; handle known compound cases explicitly if needed.
  • It matches dotfiles' trailing part oddly and rejects names ending with a dot; validate real filenames separately.
  • Extension is not a reliable indicator of actual content type — inspect bytes or MIME type for security-sensitive decisions.

Code examples

JavaScript
const re = /\.([A-Za-z0-9]+)$/g;
const text = "see photo.jpg and more";
const found = [...text.matchAll(re)].map(m => m[1] ?? m[0]);
// found holds every extracted occurrence
Python
import re

rx = re.compile(r"\.([A-Za-z0-9]+)$")
text = "see photo.jpg and more"
found = rx.findall(text)   # every occurrence (groups if present)
Java
import java.util.regex.*;

Pattern p = Pattern.compile("\\.([A-Za-z0-9]+)$");
Matcher m = p.matcher("photo.jpg");
boolean ok = m.find();   // scan for occurrences
PHP
<?php
$subject = "photo.jpg";
if (preg_match_all('/\.([A-Za-z0-9]+)$/', $subject, $m)) {
    // $m[0] is the full match; $m holds every occurrence
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

How do I get .tar.gz instead of just .gz?

Match known compound extensions first (e.g. \.(tar\.gz|tar\.bz2)$), then fall back to the simple final-extension pattern for everything else.

Can I trust the extension for file type?

No — extensions can be spoofed. For uploads and security checks, validate the actual content (magic bytes or MIME type), not just the filename extension.

Why do extraction patterns use the global flag?

Without g (or findall/preg_match_all), only the first occurrence is returned. The global flag iterates every match in the text, which is what you want when pulling all emails, URLs or tags from a document.

How do I capture just the part I want?

Wrap the target in a capturing group ( ... ) and read group 1 from each match. Use non-capturing groups (?: ... ) for structure you do not need, keeping the group numbering clean and predictable.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →