我尝试使用来自this answer的正则表达式从网址中提取YouTube视频ID。但是,我无法弄清楚如何正确格式化以使用NSRegularExpression。我已尝试转义C的反斜杠,以及使用escapedTemplateForString
和escapedPatternForString
。我还尝试在打开/关闭括号之前添加反斜杠。每个案例都会为我尝试的所有网址返回NSNotFound。
// Original: /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/
NSString *c_escaped = @"/^.*(youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#\\&\\?]*).*/";
NSString *template = [NSRegularExpression escapedTemplateForString:c_escaped]; // "/^.*(youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#\\&\\?]*).*/"
NSString *pattern = [NSRegularExpression escapedPatternForString:c_escaped]; // "\/\^\.\*\(youtu\.be\\\/\|v\\\/\|e\\\/\|u\\\/\\w\+\\\/\|embed\\\/\|v=\)\(\[\^#\\&\\\?]\*\)\.\*\/"
NSRegularExpression *expr = [NSRegularExpression regularExpressionWithPattern:c_escaped
options:0
error:&error];
NSRange range = [expr rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
NSRegularExpression *expr1 = [NSRegularExpression regularExpressionWithPattern:template
options:0
error:&error];
NSRange range1 = [expr1 rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
NSRegularExpression *expr2 = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:&error];
NSRange range2 = [expr2 rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
这些是我测试过的网址:
NSArray *urls = @[
@"//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0",
@"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
@"http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel",
@"http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub",
@"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
@"http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY",
@"http://youtu.be/6dwqZw0j_jY",
@"http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be",
@"http://youtu.be/afa-5HQHiAs",
@"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0",
@"http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel",
@"http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub",
@"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
@"http://www.youtube.com/embed/nas1rJpm7wY?rel=0",
@"http://www.youtube.com/watch?v=peFZbP64dsU",
@"http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player",
@"http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player",
@"http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player",
@"http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player",
@"http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
@"http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player",
@"http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player",
@"http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player"];