目标C:如何提取字符串的一部分(日期和电话号码)

时间:2014-10-15 22:25:45

标签: objective-c text nsstring extraction

我有一个字符串,如下所示,

NSString * aString = @"This is the 10/32/1993 and Ph: (02) 9423-2323 I want";

如何将日期和电话号码设置为两个单独的叮咬。 “9423-2323”和“10/32/1993”

3 个答案:

答案 0 :(得分:3)

使用NSDataDetector

NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber | NSTextCheckingTypePhoneNumber
                                                           error:&error];

NSString *string = @"This is the 10/32/1993 and Ph: (02) 9423-2323";
[detector enumerateMatchesInString:string
                           options:kNilOptions
                             range:NSMakeRange(0, [string length])
                        usingBlock:
^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
  NSLog(@"Match: %@", result);
}];

答案 1 :(得分:0)

我相信如果您的字符串将始终包含相同的文本但数字不同,那么您可以使用以下内容:

NSString *stringDate;
NSString *stringPhone;

stringDate  = [aString substringWithRange: NSMakeRange (12, 10)];
stringPhone = [aString substringWithRange: NSMakeRange (38, 9)];

您只需要计算日期的正确位置(即12)和手机的正确位置(即38)

答案 2 :(得分:0)

一种选择是使用NSScanner中显示的String Programming Guide

非常粗略的实施将是:

NSString * aString = @"This is the 10/32/1993 and Ph: (02) 9423-2323 I want";

NSString *phoneString;
NSString *dateString;

NSString *datePrefix = @"This is the ";
NSString *dateSuffix = @"and Ph: (02) ";
NSString *phoneSuffix = @" I want";

NSScanner *scanner= [NSScanner scannerWithString:aString];

[scanner scanString:datePrefix intoString:NULL];
[scanner scanUpToString:dateSuffix intoString:&dateString];
[scanner scanString:dateSuffix intoString:NULL];
[scanner scanUpToString:phoneSuffix intoString:&phoneString];
[scanner scanString:phoneSuffix intoString:NULL];

NSLog(@"\n%@ \n%@", dateString, phoneString);