Md1079
Md1079

Reputation: 1360

NSRegularExpression for a YouTube link

I am trying to capture a YouTube link from a string of text using NSRegularExpression although not sure how to capture the entire link I can get it to match using this:

NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:@"http://youtube.*"
                                  options:NSRegularExpressionCaseInsensitive
                                  error:&error];

Example string:

"Hello please take a look at the following: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be  For tomorrow thanks."

Any thoughts on how this could be achieved?

Upvotes: 1

Views: 349

Answers (1)

zaph
zaph

Reputation: 112857

This assumes that the URL starts with "http" or "https" and that there are no spaces in the URL and a space immediatly following the URL, this seems reasonable.

NSString *searchString = @"Hello please take a look at the following: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be For tomorrow thanks.";

NSRange   searchRange = NSMakeRange(0, [searchString length]);
NSString *pattern = @"(http[s]?://www.youtube.com\\S+)";
NSError  *error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:searchString options:0 range: searchRange];
NSRange matchRange = [match rangeAtIndex:1];
NSLog(@"matchRange: %@", NSStringFromRange(matchRange));
NSString *matchString = [searchString substringWithRange:matchRange];
NSLog(@"matchString: %@", matchString);

Output:

matchRange: {43, 60}
matchString: https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be

If you want the "www." to be optional you can use thei pattern (tip of the hat to @MikeAtNobel for the idea:

"(http[s]?://(?:www\\.)?youtube.com\\S+)"

ICU User Guide: Regular Expressions

Upvotes: 3

Related Questions