The Pattern
``regex
(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([A-Za-z0-9_-]{11})
`
Flags: g
What It Accepts and Rejects
| Input | Result |
|---|---|
https://youtu.be/dQw4w9WgXcQ | ā matches |
https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=30 | ā matches |
https://www.youtube.com/@channelname | ā rejected |
https://vimeo.com/123456789 | ā rejected |
One Capture, Four URL Shapes
The alternation covers the four forms YouTube actually serves: the youtu.be short link,
the standard watch?v= URL, the embed/ iframe source and the shorts/ path. Each
leads to the same capture group.
The ID class [A-Za-z0-9_-]{11} is exact: YouTube video IDs are always eleven characters
from that set. Pinning the length is what stops the pattern from swallowing the &t=30
that follows in a URL with parameters.
The Limits of This Pattern
The pattern extracts an ID, which is not the same as confirming a video exists, is public,
or is embeddable. Playlist URLs, channel URLs and live stream links have different shapes and
either fail to match or produce a wrong capture.
If you are embedding user-supplied links, extract the ID with this and then build your own
embed URL from it. Never pass a user-supplied URL straight into an iframe src.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs ā very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes ā (a+)+, (\w+\s?)* ā can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags ā as here ā they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .