Skip to content

Instantly share code, notes, and snippets.

@balavec
Forked from zdk/extract_youtube_id.mm
Last active August 29, 2015 14:01
Show Gist options
  • Save balavec/226a3913a884e85c01b0 to your computer and use it in GitHub Desktop.
Save balavec/226a3913a884e85c01b0 to your computer and use it in GitHub Desktop.
//
// extract_youtube_id.m
// TestRegex
//
// Created by zdk on 1/8/2013 BE.
// Copyright (c) 2013 zdk. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//test list
NSArray *youtubeURLs = [NSArray arrayWithObjects:
@"http://youtu.be/NLqAF9hrVbY",
@"http://www.youtube.com/watch?feature=player_embedded&v=DJjDrajmbIQ",
@"http://www.youtube.com/watch?v=dQw4w9WgXcQ",
@"http://www.youtube.com/embed/NLqAF9hrVbY",
@"https://www.youtube.com/embed/NLqAF9hrVbY",
@"http://www.youtube.com/watch?v=NLqAF9hrVbY",
@"http://www.youtube.com/v/dQw4w9WgXcQ",
@"http://youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
@"http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
@"http://youtube.com/watch?v=NLqAF9hrVbY",
@"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
@"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
@"http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4",
@"http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY",
@"http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec",
nil];
//construct regex pettern
//NSString *pattern = @"(?:(?:\.be\/|embed\/|v\/|\\?v=|\&v=|\/videos\/)|(?:[\\w+]+#\\w\/\\w(?:\/[\\w]+)?\/\\w\/))([\\w-_]+)";
NSString *pattern = @"(?:(?:\\.be\\/|embed\\/|v\\/|\\?v=|\\&v=|\\/videos\\/)|(?:[\\w+]+#\\w\\/\\w(?:\\/[\\w]+)?\\/\\w\\/))([\\w-_]+)";
for (NSString *url in youtubeURLs) {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: pattern
options: NSRegularExpressionCaseInsensitive
error: &error];
NSTextCheckingResult *match = [regex firstMatchInString: url
options: 0
range: NSMakeRange(0, [url length])];
if ( match ) {
NSRange videoIDRange = [match rangeAtIndex:1];
NSString *substringForFirstMatch = [url substringWithRange:videoIDRange];
NSLog(@"url: %@, Youtube ID: %@", url, substringForFirstMatch);
} else {
NSLog(@"No string matched! %@", url);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment