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
The tutorials you are probably seeing are just instructions on how to use regular expressions, which is also what you want to use in this case.
The Cocoa class you will need to use is NSRegularExpression.
Your actual regex string will depend on the format you are expecting the url to be in since it looks like youtube has several. The general function will look something like:
+ (NSString *)extractYoutubeID:(NSString *)youtubeURL
{
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"your regex string goes here" options:NSRegularExpressionCaseInsensitive error:&error];
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:youtubeURL options:0 range:NSMakeRange(0, [youtubeURL length])];
if(!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0)))
{
NSString *substringForFirstMatch = [youtubeURL substringWithRange:rangeOfFirstMatch];
return substringForFirstMatch;
}
return nil;
}
Sorry - I don't have enough rep to add a comment to the chosen answer.
After spending ages trying to find the correct syntax for the regex, I've come across this which has helped me. Hopefully it might help someone else!
NSString *regexString = @"(?<=v(=|/))([-a-zA-Z0-9_]+)|(?<=youtu.be/)([-a-zA-Z0-9_]+)";
Taken from here. This works for the following URL formats:
- (NSString*)getYoutubeVideoID:(NSString*)url {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:url
options:0
range:NSMakeRange(0, [url length])];
NSString *substringForFirstMatch;
if (match) {
NSRange videoIDRange = [match rangeAtIndex:0];
substringForFirstMatch = [url substringWithRange:videoIDRange];
}
return substringForFirstMatch;
}
Swift 2 version for @Alex answer
func getYoutubeVideoId(youtubeLink:String) -> String?{
var youtubeId:String? = nil
let pattern: String = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
do {
let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
if let regexMatch = regex.firstMatchInString(youtubeLink, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: youtubeLink.characters.count)) {
youtubeId = (youtubeLink as NSString).substringWithRange(regexMatch.range)
}
}
catch let error as NSError{
print("Error while extracting youtube id \(error.debugDescription)")
}
return youtubeId
}