Youtube Video ID From URL - Objective C

后端 未结 16 910
失恋的感觉
失恋的感觉 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条回答
  •  Happy的楠姐
    2020-12-22 23:53

    Based on this answer: PHP Regex to get youtube video ID?

    I adapted a regex for c/objc/c++ string, the important part here is that the regex doesn't get videos from facebook or other services. iOS regex is based on: ICU

    NSString *regexString = @"^(?:http(?:s)?://)?(?:www\\.)?(?:m\\.)?(?:youtu\\.be/|youtube\\.com/(?:(?:watch)?\\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)/))([^\?&\"'>]+)";
    
    NSError *error;
    NSRegularExpression *regex =
    [NSRegularExpression regularExpressionWithPattern:regexString
                                              options:NSRegularExpressionCaseInsensitive
                                                error:&error];
    NSTextCheckingResult *match = [regex firstMatchInString:message
                                                    options:0
                                                      range:NSMakeRange(0, [message length])];
    
    if (match && match.numberOfRanges == 2) {
        NSRange videoIDRange = [match rangeAtIndex:1];
        NSString *videoID = [message substringWithRange:videoIDRange];
    
        return videoID;
    }
    

    Matches:

    • youtube.com/v/vidid
    • youtube.com/vi/vidid
    • youtube.com/?v=vidid
    • youtube.com/?vi=vidid
    • youtube.com/watch?v=vidid
    • youtube.com/watch?vi=vidid
    • youtu.be/vidid
    • youtube.com/embed/vidid
    • http://youtube.com/v/vidid
    • http://www.youtube.com/v/vidid
    • https://www.youtube.com/v/vidid
    • youtube.com/watch?v=vidid&wtv=wtv
    • http://www.youtube.com/watch?dev=inprogress&v=vidid&feature=related
    • https://m.youtube.com/watch?v=vidid

    Does not match:

    • www.facebook.com?wtv=youtube.com/v/vidid
    • https://www.facebook.com/video.php?v=10155279523025107

提交回复
热议问题