objective-cxcodestringios8nsdatadetector

How to separate Phone number and Conference Code from String


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


Solution

  • 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];
        }
    }