bobsacameno
bobsacameno

Reputation: 765

iPhone address book - get phone number as string with numbers only

I am getting a phone number from the address book and I put it in an NSString* :

ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
NSString *phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);

I want to get only the numbers as a straight string (meaning without characters like (,),+,- and so on).

when I execute the code above and check it NSLog(@"phone is %@", phone); I get: phone is 1 (800) 800-8000

Actually In the Xcode console I see that before the '(' and after the ')' there is a centre dot sign which was not copied properly to this post.

My goal is to turn 1 (800) 800-8000 to this 18008008000. How can I do it?

Upvotes: 1

Views: 494

Answers (2)

Neeku
Neeku

Reputation: 3653

You can do it in so many ways.

One simple way:

NSString *phone = @"1 (800) 800-8000 home";
NSString *strippedNumber = [phone stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [phone length])];

Note: [^0-9] means any characters apart from 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9.

Upvotes: 3

Droppy
Droppy

Reputation: 9721

Use the following code:

NSString *filtered = [[phone componentsSeparatedByCharactersInSet:
    [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                         componentsJoinedByString:@""];

Upvotes: 6

Related Questions