Advertisement

Pattern library / URLs & Marketing

YouTube URL Regex (+ Video ID Extraction)

Five URL shapes, one video: youtube.com/watch?v=, youtu.be/, /shorts/, /embed/, /live/ — all ending in an 11-character ID. This pattern matches them all (mobile, http, extra query params included) and puts the video ID in capture group 4 — which is usually the part you actually wanted.

The pattern
^(https?://)?(www\.|m\.)?(youtube\.com/(watch\?v=|shorts/|embed/|live/)|youtu\.be/)([0-9A-Za-z_-]{11})([?&#].*)?$
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
https://www.youtube.com/watch?v=dQw4w9WgXcQMatchclassic watch URLTry →
https://youtu.be/dQw4w9WgXcQMatchshort domainTry →
https://www.youtube.com/shorts/aB3dEfG7hIjMatchShorts linkTry →
https://m.youtube.com/watch?v=dQw4w9WgXcQ&t=43sMatchmobile subdomain + time paramTry →
https://www.youtube.com/watch?v=shortNo matchID must be exactly 11 charactersTry →
https://vimeo.com/123456789No matchnot YouTubeTry →

Where to use it

JavaScript

const m = url.match(/^(https?:\/\/)?(www\.|m\.)?(youtube\.com\/(watch\?v=|shorts\/|embed\/|live\/)|youtu\.be\/)([0-9A-Za-z_-]{11})([?&#].*)?$/);
const id = m && m[4];  // 'dQw4w9WgXcQ'

Python

import re
Y = r'^(https?://)?(www\.|m\.)?(youtube\.com/(watch\?v=|shorts/|embed/|live/)|youtu\.be/)([0-9A-Za-z_-]{11})([?&#].*)?$'
re.match(Y, 'https://youtu.be/dQw4w9WgXcQ').group(4)

BigQuery (RE2)

SELECT REGEXP_EXTRACT(url, r'^(https?://)?(www\.|m\.)?(youtube\.com/(watch\?v=|shorts/|embed/|live/)|youtu\.be/)([0-9A-Za-z_-]{11})', 4) AS video_id

Common mistakes

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

FAQ

How do I extract the YouTube video ID?

It is capture group 4 of this pattern: 11 characters from A-Z, a-z, 0-9, underscore and hyphen. In JavaScript: url.match(PATTERN)[4].

Why does my pattern fail on youtu.be links?

youtu.be/ID is a different host with no path prefix — include the youtu.be/ branch as this pattern does, or write a second pattern for the short domain.

Does this match YouTube Shorts and live URLs?

Yes — /shorts/, /live/ and /embed/ are branches of the same group. The video ID is exactly 11 characters in every form.

GitHub URL Regex - Match Repos & Extract Owner/Repo · 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.