带有一些html标签的NSString,如何搜索<img/>标签并获取url的内容

时间:2011-06-10 18:49:30

标签: objective-c regex nsstring hpple

我有一些带有一些html标签的NSString,我如何搜索标签并获取网址的内容?我不确定我是否必须使用Hpple或简单的Regex表达式。在这两种情况下,我可以举一些例子吗?

1 个答案:

答案 0 :(得分:28)

执行此操作的一种方法是使用NSScanner。见这个例子:

NSString *url = nil;
NSString *htmlString = ...
NSScanner *theScanner = [NSScanner scannerWithString:htmlString];
// find start of IMG tag
[theScanner scanUpToString:@"<img" intoString:nil];
if (![theScanner isAtEnd]) {
    [theScanner scanUpToString:@"src" intoString:nil];
    NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@"\"'"];
    [theScanner scanUpToCharactersFromSet:charset intoString:nil];
    [theScanner scanCharactersFromSet:charset intoString:nil];
    [theScanner scanUpToCharactersFromSet:charset intoString:&url];
    // "url" now contains the URL of the img
}