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
Update Swift 4:
static func extractYoutubeVideoId(from url: String) -> String? {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
guard let range = url.range(of: pattern, options: .regularExpression) else { return nil }
return String(url[range])
}
Old answer:
A bit swifter way of @Alex's Swift 3 answer w/o the use of NSString:
We can force try the regex, because we know it is valid.
static func extractYoutubeVideoId(from url: String) -> String? {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
let range = NSRange(location: 0, length: url.utf16.count)
guard let firstMatch = regex.firstMatch(in: url, options: .init(rawValue: 0), range: range) else { return nil }
let start = String.UTF16Index(firstMatch.range.location)
let end = String.UTF16Index(firstMatch.range.location + firstMatch.range.length)
return String(url.utf16[start..
Or, if you still want NSString:
static func extractYoutubeVideoId(from url: String) -> String? {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
let range = NSRange(location: 0, length: (url as NSString).length)
guard let firstMatch = regex.firstMatch(in: url, options: .init(rawValue: 0), range: range) else { return nil }
return (url as NSString).substring(with: firstMatch.range)
}