Alex Rivera | Logout

iphone sdk - Remove all characters except for numbers 0-9 from a string

Asked 2009-07-21T16:53:13.703
16

OK So here's the plan. The XML I'm getting data from allows non-numeric text in phone number fields (for descriptions or contact names, etc). I am trying to extract only the numbers and call the tel: URL with them to initiate a call. Here's whats NOT working:

NSCharacterSet *charset = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString *number = @"(555) 555-5555 Office";
NSString *strippedNumber = [number stringByTrimmingCharactersInSet:charset];
NSString *phoneURL = [NSString stringWithFormat:@"tel:%@", strippedNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneURL]];

if there are any obvious typos, they're just typos. :)

Edit
Report

1 Answer

12

You're using a trim method, which means that it's only looking at the outer edges of the string. You're probably getting something like: "555) 555-555" as the phone number, correct?

I'm not aware of an NS(Mutable)String method along the lines of "replaceOccurrencesOfCharactersInSet:(NSCharacterSet *)set", and I admit, that'd probably be really nice to have.

Being me, I'd probably just use a regex. If you use RegexKitLite, then you can easily do:

#import "RegexKitLite.h"

NSString * number = @"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfRegex:@"[^0-9]" withString:@""];

It might be a bit overkill, but it will do exactly what you're looking for.

FYI: "[^0-9]" means "any character that's not 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9".

answered 2009-07-21T17:01:53.560

Your Answer