user739509
user739509

Reputation: 813

NSDataDetector phone numbers

I am using NSDataDetector to parse a text and retrieve the numbers. Here is my code:

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

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

for (NSTextCheckingResult *match in matches) {


        if ([match resultType] == NSTextCheckingTypePhoneNumber) {

            self.theNumber = [match phoneNumber];
        }
    }

The problem with this is that it sometime returns something like this:

Telephone: 9729957777 OR 9729957777x3547634

I don't want that to appear and to remove it would be harder then using a regex code to retrieve the numbers. Do you have any idea on how to retrieve only the number.

Upvotes: 1

Views: 804

Answers (1)

Alex Nichol
Alex Nichol

Reputation: 7510

Personally I would just use -substringWithRange: on the string to remove everything past and including the 'x' character:

NSString * myPhoneNum = @"9729957777x3547634";
NSRange r = [myPhoneNum rangeOfString:@"x"];
if (r.location != NSNotFound) {
    myPhoneNum = [myPhoneNum substringWithRange:NSMakeRange(0, r.location)];
}
NSLog(@"Fixed number: %@", myPhoneNum);

Any idea where the x3547634 comes from, anyway?

Upvotes: 2

Related Questions