Skip to content

Instantly share code, notes, and snippets.

@pietrobasso
Forked from zdk/extract_youtube_id.mm
Last active October 7, 2020 22:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pietrobasso/f067360f746f59f18287950e9bf0dbdd to your computer and use it in GitHub Desktop.
Save pietrobasso/f067360f746f59f18287950e9bf0dbdd to your computer and use it in GitHub Desktop.
A Regex to extract YouTube video ids from the given list of youtube URLs in Swift 4
//: Playground - noun: a place where people can play
//
// Created by Pietro Basso on 29/06/2018.
// Copyright (c) 2018 Pietro Basso. All rights reserved.
//
let urls = ["http://youtu.be/NLqAF9hrVbY",
"http://www.youtube.com/watch?feature=player_embedded&v=DJjDrajmbIQ",
"http://www.youtube.com/watch?v=dQw4w9WgXcQ",
"http://www.youtube.com/embed/NLqAF9hrVbY",
"https://www.youtube.com/embed/NLqAF9hrVbY",
"http://www.youtube.com/watch?v=NLqAF9hrVbY",
"http://www.youtube.com/v/dQw4w9WgXcQ",
"http://youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
"http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
"http://youtube.com/watch?v=NLqAF9hrVbY",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
"http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4",
"http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY",
"http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec"]
/**
Extract YouTube video id from url.
Inspired from:
- [NSRegularExpression - NSHipster](http://nshipster.com/nsregularexpression/)
- [A stupid Regex to extract Youtube id from the given list of youtube URLs in Objective-C - zdk on GitHub](https://gist.github.com/zdk/4481771)
*/
func extractYouTubeId(from url: String) -> String? {
let typePattern = "(?:(?:\\.be\\/|embed\\/|v\\/|\\?v=|\\&v=|\\/videos\\/)|(?:[\\w+]+#\\w\\/\\w(?:\\/[\\w]+)?\\/\\w\\/))([\\w-_]+)"
let regex = try? NSRegularExpression(pattern: typePattern, options: .caseInsensitive)
return regex
.flatMap { $0.firstMatch(in: url, range: NSMakeRange(0, url.count)) }
.flatMap { Range($0.range(at: 1), in: url) }
.map { String(url[$0]) }
}
print(urls
.map { extractYouTubeId(from: $0) }
.compactMap { $0 }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment