Go (RE2)

YouTube Video ID in GO

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

Try it in the GO tester →

Pattern

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

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w\-]{11})`)
	input := `https://www.youtube.com/watch?v=dQw4w9WgXcQ`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

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)