Pattern library / Extract & Replace
File Extension Regex
Whether you are filtering downloads in analytics, auditing a media library or parsing filenames, the shape is the same: a literal dot followed by letters at the end of the string. The anchored version validates; the unanchored version extracts.
How the pattern works
\.— a literal dot (the escape is mandatory; unescaped.matches any character).([a-zA-Z0-9]+)$— extension letters/digits until end of string; the capture group holds the extension without the dot.- Compound extensions:
\.([a-z0-9]+)$only catches the last segment (gz). Fortar.gzas one unit use\.([a-z0-9]{1,8})$plus a whitelist, or match known doubles explicitly. - To validate a whitelist (images only):
\.(png|jpe?g|gif|webp|avif)$with theiflag.
Test it: match & no-match examples
Every row is loaded straight into the tester — click Try to see the match live:
| Input | Result | Why | |
|---|---|---|---|
/docs/ga4-cheatsheet.pdf | Match | captures pdf | Try → |
photo_v2.PNG | Match | case-insensitive letters | Try → |
archive.tar.gz | Match | captures last ext: gz | Try → |
README | No match | no extension | Try → |
file.name. | No match | empty extension | Try → |
/v1.2/users | No match | dot not at end | Try → |
Where to use it
JavaScript
const m = '/docs/report.pdf'.match(/\.([a-zA-Z0-9]+)$/); const ext = m && m[1].toLowerCase(); // 'pdf'
Python (media audit)
import re, os exts = [m.group(1) for m in (re.search(r'\.([a-zA-Z0-9]+)$', f) for f in files) if m]
BigQuery (downloads report)
WHERE REGEXP_CONTAINS(page_path, r'\.(pdf|docx?|xlsx?|csv)$')
Common mistakes
- Unescaped dot matches anything —
.pdfmatches "apdf". Always\.. - Query strings break the anchor:
file.pdf?v=2fails$— strip[?#].*first. - Multi-dot extensions need a decision: last segment only (default) or a known-doubles list.
FAQ
How do I match several extensions at once?
Alternation with a whitelist: \.(pdf|docx?|xlsx?|csv)$ — and add the i flag for case-insensitive matching.
Why does archive.tar.gz give me gz?
Because $ anchors to the end and the pattern takes the final dot-run. To treat tar.gz as a unit, match it explicitly: \.(tar\.gz|tgz)$.
How do I ignore query strings?
Strip before matching: value.split(/[?#]/)[0], then apply the extension pattern.
Related patterns
Extract Domain from URL — Regex Capture Group · URL Regex — Match http/https Links (Practical) · Remove Query Parameters with Regex (Replace Example)
For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.