YouTube 的 NSRegularExpression link

NSRegularExpression for a YouTube link

我正在尝试使用 NSRegularExpression 从一串文本中捕获 YouTube link,但不确定如何捕获整个 link 我可以使用以下命令使其匹配:

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

示例字符串:

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

关于如何实现这一点有什么想法吗?

这假设 URL 以 "http" 或 "https" 开头,并且 URL 和 [=25] 中没有 space =]紧接着URL,这似乎是合理的。

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);

输出:

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

如果您希望 "www." 是可选的,您可以使用他们的模式(向@MikeAtNobel 致敬:

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

ICU 用户指南:Regular Expressions