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
Swift 3 version for @Alex answer
func extractYoutubeIdFromLink(link: String) -> String? {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
guard let regExp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else {
return nil
}
let nsLink = link as NSString
let options = NSRegularExpression.MatchingOptions(rawValue: 0)
let range = NSRange(location: 0,length: nsLink.length)
let matches = regExp.matches(in: link as String, options:options, range:range)
if let firstMatch = matches.first {
debugPrint(firstMatch)
return nsLink.substring(with: firstMatch.range)
}
return nil
}