iphone sdk - Remove all characters except for numbers 0-9 from a string [duplicate]
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. :)
Solution 1:
Simpler using iOS APIs only:
NSString * number = @"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];
Solution 2:
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".
Solution 3:
Although this has already been answered/accepted, I have a better solution without needing an external SDK. Create an additional NSString method in a category like this:
@interface NSString (Helpers)
- (NSString*)stringByRemovingCharactersInSet:(NSCharacterSet*)set;
@end
@implementation NSString (Helpers)
- (NSString*)stringByRemovingCharactersInSet:(NSCharacterSet*)set
{
NSArray* components = [self componentsSeparatedByCharactersInSet:set];
return [components componentsJoinedByString:@""];
}
@end
Now you can use stringByRemovingCharactersInSet instead of stringByTrimmingCharactersInSet. However I'd also recommend another slight change to your example code, to support the '+' character in international numbers, as follows:
NSString* number = @"(555) 555-555 Office";
NSCharacterSet* phoneChars = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"];
NSString* strippedNumber = [number stringByRemovingCharactersInSet:[phoneChars invertedSet]];
NSString* urlString = [NSString stringWithFormat:@"tel:%@", strippedNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];