Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/105.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 用于YouTube链接的NSRegularExpression_Ios_Objective C_Regex_Nsregularexpression - Fatal编程技术网

Ios 用于YouTube链接的NSRegularExpression

Ios 用于YouTube链接的NSRegularExpression,ios,objective-c,regex,nsregularexpression,Ios,Objective C,Regex,Nsregularexpression,我正在尝试使用NSRegularExpression从文本字符串捕获YouTube链接,但不确定如何捕获整个链接,我可以使用以下方法使其匹配: NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http://youtube.*" options:NSR

我正在尝试使用NSRegularExpression从文本字符串捕获YouTube链接,但不确定如何捕获整个链接,我可以使用以下方法使其匹配:

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中没有空格,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);
输出:

匹配范围:{43,60}
匹配字符串:

如果您希望“www.”是可选的,您可以使用i模式(帽尖到@MikeAtNobel)来表达您的想法:

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

ICU用户指南:

例如URLObjC或Swift编辑?看起来像Objective-C。ObjC是感谢的语言为什么在正则表达式中的
S
前面有两个反斜杠?因为“C”语言需要它。编译器生成警告:未知转义序列“\”。是否可以在字符串中获取捕获的匹配项的NSRange?该范围已经存在,并且正在
NSLog()
中使用,以单独获取:
NSRange matchRange=[match rangeAtIndex:1];
。我已将此添加到答案中。