Parse any YouTube URL into a video ID

The pipeline starts with a URL the user pastes in. YouTube has about half a dozen URL formats in the wild: watch URLs, shortened youtu.be links, embed URLs, and sometimes just the raw 11-character ID. We need one function that handles them all.

The video ID is always 11 characters long and uses the pattern [0-9A-Za-z_-]. That regex class is the anchor for every URL we will parse.

From pasted URL to transcript chunks

The ingestion flow for a single video, from raw URL to the snippets we will chunk and embed.

transcript.py
python
import re


def extract_video_id(url: str) -> str | None:
    """Extract video ID from various YouTube URL formats."""
    patterns = [
        r"(?:v=|\/)([0-9A-Za-z_-]{11}).*",
        r"(?:youtu\.be\/)([0-9A-Za-z_-]{11})",
        r"(?:embed\/)([0-9A-Za-z_-]{11})",
        r"^([0-9A-Za-z_-]{11})$",
    ]
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    return None

Four patterns cover every URL shape we see in the wild. The function returns None when nothing matches, so the caller can show a clear error.

That works for standard watch URLs, but not for youtu.be shortlinks, embed URLs, or raw video IDs. The regex approach handles every format in one pass. It is also forgiving about extra query parameters like timestamps or playlist refs.

Quiz: Quiz

Loading practice…