2015-08-18 30 views
1

我試圖捕捉使用NSRegularExpression雖然不知道是文本字符串一個YouTube鏈接如何捕捉整個鏈路我可以得到它使用此匹配: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

編輯例如URL – Md1079

+0

ObjC或雨燕看起來像Objective-C的。 –

+0

ObjC是語言感謝 – Md1079

回答

3

這假定URL以「http」或「https」開頭,並且網址中沒有空格,並且在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」。是可選的,您可以使用THEI帽子的模式(尖@MikeAtNobel爲理念:

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

ICU用戶指南:Regular Expressions

+0

爲什麼在正則表達式中'S'前面有2個反斜槓? – dudeman

+1

因爲「C」語言需要它。 – zaph

+0

編譯器產生一個警告:未知的轉義序列'\'。 – zaph