Regex for YouTube video ID from a URL

Use /^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{11})(?:[?&#].*)?$/ to check that a whole string is a valid for YouTube video ID from a URL. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{11})(?:[?&#].*)?$/
Open in Regex Tester
InputResultGroups
https://www.youtube.com/watch?v=dQw4w9WgXcQ✓ MatchdQw4w9WgXcQ
https://youtu.be/dQw4w9WgXcQ?t=42✓ MatchdQw4w9WgXcQ
youtube.com/shorts/abcdefghijk✓ Matchabcdefghijk
https://m.youtube.com/watch?v=dQw4w9WgXcQ&list=PL1✓ MatchdQw4w9WgXcQ
https://vimeo.com/123456✗ No match
https://www.youtube.com/watch?v=short✗ No match
https://youtube.com/@channel✗ No match

How the pattern works

PartMeaning
(?:https?:\/\/)?(?:www\.|m\.)?Optional scheme and www or m subdomain
youtube\.com\/(?:watch\?v=|embed\/|shorts\/)Watch, embed and Shorts URLs
youtu\.be\/Or the short youtu.be links
([\w-]{11})Group 1: the 11-character video ID
(?:[?&#].*)?Optional extra parameters such as &t=42 or &list=…

Code examples

JavaScript

const re = /^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{11})(?:[?&#].*)?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'(?:https?://)?(?:www\.|m\.)?(?:youtube\.com/(?:watch\?v=|embed/|shorts/)|youtu\.be/)([\w-]{11})(?:[?&#].*)?', value))

PHP

preg_match('/^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{11})(?:[?&#].*)?$/', $value) === 1;

Notes and limitations

Group 1 holds the video ID, which you can drop into https://www.youtube.com/embed/ID or the thumbnail URL https://i.ytimg.com/vi/ID/hqdefault.jpg. The watch URL must have v= as its first parameter.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for YouTube video ID from a URL?
/^(?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{11})(?:[?&#].*)?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: https://www.youtube.com/watch?v=dQw4w9WgXcQ, https://youtu.be/dQw4w9WgXcQ?t=42, youtube.com/shorts/abcdefghijk, https://m.youtube.com/watch?v=dQw4w9WgXcQ&list=PL1. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.