0

我要做的是提取存储在 NSString 中的锚标记的内容。

例如,如果我有一个包含以下内容的字符串:

<a href="/url?q=https://kindle.amazon.com/&amp;sa=U&amp;ei=GdiWT5uCEI6BhQfihoTzDQ&amp;ved=0CCUQFjAB&amp;usg=AFQjCNEoRolsgoynLNS0H60VWz-9EaQdtw">Amazon <b>Kindle</b>: Welcome</a>

我将如何提取锚标记的内容,以便获得以下内容:

https://kindle.amazon.com/&amp;sa=U&amp;ei=GdiWT5uCEI6BhQfihoTzDQ&amp;ved=0CCUQFjAB&amp;usg=AFQjCNEoRolsgoynLNS0H60VWz-9EaQdtw

任何帮助将不胜感激!

我完全被难住了,而这应该很简单?下面发布的答案不断返回null。

4

2 回答 2

0

One Possible solution is by using NSScanner -

NSString *urlString = nil;
NSString *htmlString = @"<a href=\"/url?q=https://kindle.amazon.com/&amp;sa=U&amp;ei=GdiWT5uCEI6BhQfihoTzDQ&amp;ved=0CCUQFjAB&amp;usg=AFQjCNEoRolsgoynLNS0H60VWz-9EaQdtw\">Amazon <b>Kindle</b>: Welcome</a>";

NSScanner *scanner = [NSScanner scannerWithString:htmlString];

[scanner scanUpToString:@"<a" intoString:nil];
if (![scanner isAtEnd]) {
    [scanner scanUpToString:@"http" intoString:nil];
    NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@">"];
    [scanner scanUpToCharactersFromSet:charset intoString:&urlString];
}
NSLog(@"%@", urlString);

In Logs - https://kindle.amazon.com/&sa=U&ei=GdiWT5uCEI6BhQfihoTzDQ&ved=0CCUQFjAB&usg=AFQjCNEoRolsgoynLNS0H60VWz-9EaQdtw

于 2012-04-24T17:07:46.930 回答
0

如果您可以要求 Lion,那么您可以使用NSRegularExpression.

NSString* stringToSearch = @"<a href=\"/url?q=https://kindle.amazon.com/&amp;sa=U&amp;ei=GdiWT5uCEI6BhQfihoTzDQ&amp;ved=0CCUQFjAB&amp;usg=AFQjCNEoRolsgoynLNS0H60VWz-9EaQdtw\">Amazon <b>Kindle</b>: Welcome</a>";

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"href\\s*=\\s*\"\\/url\\?q=([^\"]*)\""
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSTextCheckingResult* match = [regex firstMatchInString:stringToSearch options:0 range:NSMakeRange(0, [stringToSearch length])];
if(match.numberOfRanges == 2)
{
    NSRange capture = [match rangeAtIndex:1];
    NSString* URLString = [stringToSearch substringWithRange:capture];
    NSLog(@"%@",URLString);
}
于 2012-04-24T23:55:26.433 回答