简体   繁体   中英

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?

Use the following code:

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM