Youtube Video Id from URL - Swift3

后端 未结 8 2291
眼角桃花
眼角桃花 2021-02-15 12:52

Basically I have a Youtube URL as string, I want to extract the video Id from that URL. I found some code in objective c that is as below:

NSError *error = NULL;         


        
8条回答
  •  离开以前
    2021-02-15 13:21

    Safer version (without force unwrapping !):

    extension String {
        var youtubeID: String? {
            let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
    
            let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
            let range = NSRange(location: 0, length: count)
    
            guard let result = regex?.firstMatch(in: self, range: range) else {
                return nil
            }
    
            return (self as NSString).substring(with: result.range)
        }
    }
    

    Examples:

    "https://www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    "https://youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    "www.youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    "youtube.com/watch?v=C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    
    "https://youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    "youtu.be/C0DPdy98e4c".youtubeID // "C0DPdy98e4c"
    

    Credits: Usman Nisar's answer

提交回复
热议问题