Reputation: 32207
I'm trying to do a basic regular expression in xcode and it's not cooperating.
NSString *urlString = @"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/.*?v=(.*)&.*/" options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *fmis = [regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if(fmis) {
NSRange match = [fmis range];
NSLog(@"%i", match.location);
}
essentially, I'm just trying to suck 3uyaO745g0s
out of the urlString. I assume a regular expression is the best way? Thanks for looking my question.
** EDIT **
sometimes the url will look like this: http://www.youtube.com/watch?v=3uya0746g0s
and I have to capture the vid from that as well.
Upvotes: 1
Views: 381
Reputation: 114
There are many types of Youtube URLs. Maybe you can try this
NSString *urlString = @"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSString *regEx = @"[a-zA-Z0-9\\-\\_]{11}";
NSRange idRange = [urlString rangeOfString:regEx options:NSRegularExpressionSearch];
NSString *youtubeID = [urlString substringWithRange:idRange];
I found this regular expression here. And you don't have to use NSRegularExpression
for simple search:)
I think this is pretty good solution but if you want more reliable result, then try another regular expression in that answer.
Upvotes: 1
Reputation: 35626
I think it's much easier to create an NSURL
object and let it do its magic for you:
NSString *urlString = @"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSURL *url = [NSURL URLWithString:urlString];
// Since you're targeting the last component of the url
NSString *myMatch = [url lastPathComponent]; //=> 3uyaO745g0s
You can find more on how to access various parts of an NSURL
object here
Upvotes: 3