Forked from pietrobasso/ExtractYouTubeId.playground
Created
January 21, 2019 07:32
-
-
Save theRealGupta/7f298383639592e8ec95293ac85e98af 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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