Ben Harris Ben Harris - 1 year ago 87
Objective-C Question

Remove all but numbers from NSString

I have an NSString (phone number) with some parenthesis and hyphens as some phone numbers are formatted. How would I remove all characters except numbers from the string?

Answer Source

Old question, but how about:

  NSString *newString = [[origString componentsSeparatedByCharactersInSet:
            	[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 

It explodes the source string on the set of non-digits, then reassembles them using an empty string separator. Not as efficient as picking through characters, but much more compact in code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download