Skip to main content
hank-builds.com

File Extension regex

Extracts file extension from a filename.

/\.(\w+)$/gm

What it matches

The final dot and the word characters that follow it at the end of a line. Anchoring to $ with the m flag is what makes it the extension rather than any dot in the name, so archive.tar.gz yields .gz and dots in the directory names of a path are left alone.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

\. Group \w $

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
m^ and $ match the start/end of each line, not just the string
\.Literal "."
\w+Word character (a-z, A-Z, 0-9, _), one or more
$End of string

Test cases

Matches

  • index.html
  • style.css
  • archive.tar.gz

Does not match

  • README
  • file.

Caveats

Dotfiles are indistinguishable from extensions here: .gitignore matches, with gitignore as the extension. A trailing dot with nothing after it does not match, and neither does a file with no dot at all. \w stops at hyphens, so a compound extension is only ever reported as its last segment.

More common patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.