【问题标题】:How can I parse the src property of an iframe tag in Objective-C?如何在 Objective-C 中解析 iframe 标签的 src 属性?
【发布时间】:2012-08-17 06:45:22
【问题描述】:

我有以下字符串:

<iframe width="1280" height="720" src="http://www.youtube.com/embed/Pb55ep-DrSo?wmode=opaque&autoplay=1&fs=1&feature=oembed&showinfo=0&autohide=1&controls=0" frameborder="0" allowfullscreen></iframe>

我想提取 src 属性,但不确定如何在 Objective-C 中解析它?

【问题讨论】:

  • 你试过 NSXMLParser 了吗?

标签: iphone objective-c cocoa iframe nsstring


【解决方案1】:

这很难看,但它有效:

NSString* str = @"<iframe width=\"1280\" height=\"720\" src=\"http://www.youtube.com/embed/Pb55ep-DrSo?wmode=opaque&autoplay=1&fs=1&feature=oembed&showinfo=0&autohide=1&controls=0\" frameborder=\"0\" allowfullscreen></iframe>";
str = [str substringFromIndex:[str rangeOfString:@"src=\""].location+[str rangeOfString:@"src=\""].length];
str = [str substringToIndex:[str rangeOfString:@"\""].location ];
NSLog(@"Str %@",str);

我测试了它,它输出:

2012-08-17 09:16:55.285 TEST[24413:c07] Str http://www.youtube.com/embed/Pb55ep-DrSo?wmode=opaque&autoplay=1&fs=1&feature=oembed&showinfo=0&autohide=1&controls=0

【讨论】:

    【解决方案2】:

    这是获取 src 属性的正则表达式,如果您需要使用一些正则表达式生成器来验证它

    src[\s]*=[\s]*"([^"]*)"
    

    这是您可以在程序中使用的完整代码,

    NSString *searchedString = @"<iframe width=\"1280\" height=\"720\" src=\"http://www.youtube.com/embed/Pb55ep-DrSo?wmode=opaque&autoplay=1&fs=1&feature=oembed&showinfo=0&autohide=1&controls=0\" frameborder=\"0\" allowfullscreen></iframe>";
    NSError* error = nil;
    
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"src[\s]*=[\s]*\"([^\"]*)\"" options:0 error:&error];
    NSArray* matches = [regex matchesInString:searchedString options:0 range:NSMakeRange(0, [searchedString length])];
    for ( NSTextCheckingResult* match in matches )
    {
        NSString* matchText = [searchedString substringWithRange:[match range]];
        NSLog(@"match: %@", matchText);
        NSRange group1 = [match rangeAtIndex:1];
        NSLog(@"group1: %@", [searchedString substringWithRange:group1]);
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多