Tôi đang sử dụng mã sau đây trên ứng dụng iPhone của mình, được lấy từ http://tinyurl.com/remarkablepixels để trích xuất tất cả các URL từ mã .html sọc.Sử dụng NSRegularExpression để trích xuất URL trên iPhone
Tôi chỉ có thể trích xuất URL đầu tiên, nhưng tôi cần một mảng chứa tất cả các URL. NSArray của tôi không trả về NSStrings cho mỗi URL, nhưng chỉ mô tả đối tượng.
Làm cách nào để làm cho số arrayOfAllMatches
trả về tất cả các URL, dưới dạng NSStrings?
-(NSArray *)stripOutHttp:(NSString *)httpLine {
// Setup an NSError object to catch any failures
NSError *error = NULL;
// create the NSRegularExpression object and initialize it with a pattern
// the pattern will match any http or https url, with option case insensitive
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&error];
// create an NSRange object using our regex object for the first match in the string httpline
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];
NSArray *arrayOfAllMatches = [regex matchesInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];
// check that our NSRange object is not equal to range of NSNotFound
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
// Since we know that we found a match, get the substring from the parent string by using our NSRange object
NSString *substringForFirstMatch = [httpLine substringWithRange:rangeOfFirstMatch];
NSLog(@"Extracted URL: %@",substringForFirstMatch);
NSLog(@"All Extracted URLs: %@",arrayOfAllMatches);
// return all matching url strings
return arrayOfAllMatches;
}
return NULL;
}
Đây là sản lượng NSLog của tôi:
Extracted URL: http://mydomain.com/myplayer
All Extracted URLs: (
"<NSExtendedRegularExpressionCheckingResult: 0x106ddb0>{728, 53}{<NSRegularExpression: 0x106bc30> http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
"<NSExtendedRegularExpressionCheckingResult: 0x106ddf0>{956, 66}{<NSRegularExpression: 0x106bc30> http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
"<NSExtendedRegularExpressionCheckingResult: 0x106de30>{1046, 63}{<NSRegularExpression: 0x106bc30> http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}",
"<NSExtendedRegularExpressionCheckingResult: 0x106de70>{1129, 67}{<NSRegularExpression: 0x106bc30> http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)? 0x1}"
)
đẹp! Làm việc như người ở! Cảm ơn rất nhiều jonkroll! – Winston
Hoạt động awesomely! Có thể lấy tiêu đề từ sau> đến <. như nếu url là Google bạn có thể nhận được "Google"? – Maximilian