1

I have a string like the below format,

Call-in toll-free number: 180012345678 (India)

Call-in number: +44-(0)123456789 (United Kingdom)

UK toll free : 12345678910

https://www.google.com/

Conference Code: 123 456 56789

How can I separate the Phone numbers from this string in Objective-C

Vineesh TP
  • 7,755
  • 12
  • 66
  • 130

2 Answers2

3

You could use the NSDataDetector (https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSDataDetector_Class/)

Following types are supported:

NSTextCheckingTypeOrthography        = 1ULL << 0,
NSTextCheckingTypeSpelling           = 1ULL << 1,
NSTextCheckingTypeGrammar            = 1ULL << 2,
NSTextCheckingTypeDate               = 1ULL << 3,
NSTextCheckingTypeAddress            = 1ULL << 4,
NSTextCheckingTypeLink               = 1ULL << 5,
NSTextCheckingTypeQuote              = 1ULL << 6,
NSTextCheckingTypeDash               = 1ULL << 7,
NSTextCheckingTypeReplacement        = 1ULL << 8,
NSTextCheckingTypeCorrection         = 1ULL << 9,
NSTextCheckingTypeRegularExpression  = 1ULL << 10
NSTextCheckingTypePhoneNumber        = 1ULL << 11,
NSTextCheckingTypeTransitInformation = 1ULL << 12

ex.

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

NSUInteger numberOfMatches = [detector numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];

NSArray *matches = [detector matchesInString: stringoptions:0 range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    if ([match resultType] == NSTextCheckingTypePhoneNumber) {
        NSString *phoneNumber = [match phoneNumber];
    }
}
  • I got the Phone number by using the code, Thanks. But, I couldn't separate Conference code . How to get it by using NSDataDetector. – Vineesh TP Jul 20 '15 at 04:35
  • for the conference code you could use a regular expression. If the format is always the same you could simply use `\d{3} \d{3} \d{5}` as regex and use the `NSRegularExpression` class. – Daniel Albertini Jul 20 '15 at 08:33
0

Check this code from another thread very similar to your question: https://stackoverflow.com/a/20230333/1658831

Community
  • 1
  • 1
Pauls
  • 2,596
  • 19
  • 19