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
There is a lot of good answers here but I thought it might be beneficial to some to parse multiple video_ID from a string. This could be a web page or an array of different URL.
Example of page content
NSString *content = @"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo,http://youtu.be/NLqAF9hrVbY,http://www.youtube.com/watch?v=NLqAF9hrVbY,http://facebook.com,http://www.youtube.com/watch?v=cAcqdjLCN7s";
Method
-(NSArray *)extractVideos:(NSString *)content {
NSString *extractRegex = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)"
NSMutableArray *extractedContent = [[NSMutableArray alloc] init];
if ([content hasPrefix:@"http://"] || [content hasPrefix:@"https://"]) {
NSURL *extractURL = [NSURL URLWithString:content];
if ([extractURL.host rangeOfString:@"youtu"].location != NSNotFound) {
NSRegularExpression *extractRegex = [NSRegularExpression regularExpressionWithPattern:extractRegex options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *extractResults = [extractRegex matchesInString:content options:0 range:NSMakeRange(0, content.length)];
for (NSTextCheckingResult *match in extractResults) {
[extractedContent addObject:[content substringWithRange:match.range]];
}
}
}
return extractedContent;
}
Output
(
NLqAF9hrVbY,
QLqAF9eeVbY,
cAcqdjLCN7s
)
Credit to @Alex for the Regex