Skip to content

Instantly share code, notes, and snippets.

@DisappearPing
Last active March 10, 2016 06:51
Show Gist options
  • Save DisappearPing/11f8c10f6946b31c770b to your computer and use it in GitHub Desktop.
Save DisappearPing/11f8c10f6946b31c770b to your computer and use it in GitHub Desktop.
String extension for getting Youtube id from URL
import Foundation
/*
this extension cover these case
www.youtube.com/v/id
www.youtube.com?v=vid
http://www.youtube.com/watch?v=id&feature=youtu.be
http://www.youtube.com/watch?v=id
youtube.be/id
http://www.youtube.com/watch?feature=player_detailpage&v=id#t=31s
www.youtube.com/watch?v=id&feature=youtu.be
www.youtube.com/watch?v=id
www.youtube.com/watch?feature=player_detailpage&v=id#t=31s
www.youtube.com/embed/id
from stackoverflow : http://stackoverflow.com/a/27796287
ex:
let test = "https://www.youtube.com/embed/ZAF3u78Q9EM".parserYTIDFromURL()
console :
test = ZAF3u78Q9EM
*/
extension String {
func parserYTIDFromURL() -> String {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
do{
let regExp = try NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
let array = regExp.matchesInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count))
if array.count > 0{
let result: NSTextCheckingResult = array.first!
return String((self as NSString).substringWithRange(result.range))
}
}catch{
return ""
}
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment