1

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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
  • 1
    For your second example you could grab it by doing something like this `[[[url query] componentsSeparatedByString:@"="] lastObject]`. Note that if you got more than one parameters in your query you should implement additional logic to grab only `v`'s value... but you get the idea... Also, RestKit has a nice category for doing exactly that. Find out more here => http://restkit.org/api/0.10.3/Categories/NSString+RKAdditions.html – Alladinian Nov 16 '12 at 14:42

2 Answers2

3

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

Alladinian
  • 34,483
  • 6
  • 89
  • 91
1

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.

Community
  • 1
  • 1
hanjae
  • 114
  • 4