Youtube Video Id from URL - Swift3

后端 未结 8 2294
眼角桃花
眼角桃花 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:22

    Your first problem is you are not escaping ? in your expression. ? is reserved character and if you want to use it in your expressions, you must escape with \ and since \ is used also to escape " character you must escape ? with double backslash something like \\?. So according to above information, following code correctly extracts the videoId

    let youtubeURL = "https://www.youtube.com/watch?v=uH8o-JTHJdM"
    let regex = try! NSRegularExpression(pattern: "\\?.*v=([^&]+)", options: .caseInsensitive)
    let match = regex.firstMatch(in: youtubeURL, options: [], range: NSRange(location: 0, length: youtubeURL.characters.count))
    if let videoIDRange = match?.rangeAt(1) {
        let substringForFirstMatch = (youtubeURL as NSString).substring(with: videoIDRange)
    } else {
        //NO video URL
    }
    

提交回复
热议问题