我正在尝试使用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."
有关如何实现这一目标的任何想法?
答案 0 :(得分:3)
这假设URL以“http”或“https”开头,并且URL中没有空格,并且URL后面有一个空格,这似乎是合理的。
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<type>jar</type>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>xalan</artifactId>
<groupId>xalan</groupId>
</exclusion>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
</exclusions>
</dependency>
输出:
matchRange:{43,40}
matchString:https://www.youtube.com/watch?v=C-UwOWB9Io4&feature=youtu.be
如果你想要“www。”作为选择你可以使用thei模式(@MikeAtNobel的帽子提示:
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);
ICU用户指南:Regular Expressions