Python (re)

YouTube Video ID in PY

Extract 11-character YouTube video IDs from long URLs, short URLs, or embed URLs.

Try it in the PY tester →

Pattern

regexPY
(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w\-]{11})   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w\-]{11})")
input_text = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

Matches any of three URL forms (watch?v=, youtu.be/, embed/) and captures the 11-character video ID that follows. The ID uses word characters and hyphens.

Examples

Input

https://www.youtube.com/watch?v=dQw4w9WgXcQ

Matches

  • youtube.com/watch?v=dQw4w9WgXcQ

Input

https://youtu.be/dQw4w9WgXcQ

Matches

  • youtu.be/dQw4w9WgXcQ

Input

not a youtube url

No match

Same pattern, other engines

← Back to YouTube Video ID overview (all engines)