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
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:
Does not match: