如何在 Objective-C 的字符串中找到非长度指定的子字符串?
我有生以来第一次尝试为开源软件做出贡献.因此,我正在尝试帮助解决这张票,因为它似乎是一个很好的初学者票".
I'm trying, for the first time in my life, to contribute to open source software. Therefore I'm trying to help out on this ticket, as it seems to be a good "beginner ticket".
我已成功从 Twitter API 获取字符串:但是,它采用以下格式:
I have successfully got the string from the Twitter API: however, it's in this format:
<a href="http://twitter.com" rel="nofollow">Mac 版推文</a>
我想从这个字符串中提取的是 URL (http://twitter.com
) 和 Twitter 客户端的名称 (Tweetie for Mac
).我怎样才能在 Objective-C 中做到这一点?由于 URL 不同,我无法搜索指定的索引,客户端名称也是如此.
What I want to extract from this string is the URL (http://twitter.com
) and the name of the Twitter client (Tweetie for Mac
). How can I do this in Objective-C? As the URL's aren't the same I can't search for a specified index, and the same applies for the client name.
假设您已经拥有 HTML 链接并且没有解析整个 HTML 页面.
Assuming you have the HTML link already and aren't parsing an entire HTML page.
//Your HTML Link
NSString *link = [urlstring text];
//Length of HTML href Link
int length = [link length];
//Range of the first quote
NSRange firstQuote = [link rangeOfString:@"\""];
//Subrange to search for another quote in the HTML href link
NSRange nextQuote = NSMakeRange(firstQuote.location+1, length-firstQuote.location-1);
//Range of the second quote after the first
NSRange secondQuote = [link rangeOfString:@"\"" options:NSCaseInsensitiveSearch range:nextQuote];
//Extracts the http://twitter.com
NSRange urlRange = NSMakeRange(firstQuote.location+1, (secondQuote.location-1) - (firstQuote.location));
NSString *url = [link substringWithRange:urlRange];
//Gets the > right before Tweetie for Mac
NSRange firstCaret = [link rangeOfString:@">"];
//This appears at the start of the href link, we want the next one
NSRange firstClosedCaret = [link rangeOfString:@"<"];
NSRange nextClosedCaret = NSMakeRange(firstClosedCaret.location+1, length-firstClosedCaret.location-1);
//Gets the < right after Tweetie for Mac
NSRange secondClosedCaret = [link rangeOfString:@"<" options:NSCaseInsensitiveSearch range:nextClosedCaret];
//Range of the twitter client
NSRange rangeOfTwitterClient = NSMakeRange(firstCaret.location+1, (secondClosedCaret.location-1)-(firstCaret.location));
NSString *twitterClient = [link substringWithRange:rangeOfTwitterClient];