I basically have a Youtube url as an NSString, but I need to extract the video id that is displayed in the url. I found many tutorials on how to do this in php or and other
Here is the swift version using @jt_ik's regex:
func extractYoutubeID(youtubeURL: String) -> String {
var error: NSError?
let pattern: String = "(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
let regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
if error == nil {
if let regexMatch = regex.firstMatchInString(youtubeURL, options: nil, range: NSRange(location: 0, length: youtubeURL.utf16Count)) {
return (youtubeURL as NSString).substringWithRange(regexMatch.range)
}
// Handle no match here
return ""
} else {
// Handle error here
println(error?.userInfo)
return ""
}
}