Youtube Video ID From URL - Objective C

后端 未结 16 963
失恋的感觉
失恋的感觉 2020-12-22 23:23

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

16条回答
  •  忘掉有多难
    2020-12-22 23:34

    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)
    }
    

提交回复
热议问题