這正是NSDataDetector的原因。
@interface NSString (HASAdditions)
- (NSArray *)detectedDates;
@end
@implementation NSString (HASAdditions)
- (NSArray *)detectedDates {
NSError *error = nil;
NSDataDetector *dateDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
if (!dateDetector) return nil;
NSArray *matches = [dateDetector matchesInString:self options:kNilOptions range:NSMakeRange(0, self.length)];
NSMutableArray *dates = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
if (match.resultType == NSTextCheckingTypeDate) {
[dates addObject:match.date];
}
}
return dates.count ? [dates copy] : nil;
}
你可以叫它像這樣:
我在NSString的類別上進行的方法
NSArray *dates = [@"402 Garcia 01/08/15 10:26 Observaciones del huésped" detectedDates];
你可以閱讀更多關於NSDataDetector超過NSHipster
來源
2015-01-09 13:38:47
HAS