How the pattern works
| Part | Meaning |
|---|---|
(?: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 falsePython
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.