I am trying to remove all of the non-numeric characters from an NSString
, but I also need to keep the spaces. Here is what I have been using.
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
If I give it a NSString of Test 333 9599 999
It will return 3339599999
but I need to keep the spaces in.
How can I do this?
In brief, you can use NSCharacterSet to examine only those chars that are interesting to you and ignore the rest.
This prints
333 9599 999
, which I think is what you're after. It also removes non numeric characters that may be in the middle of the string, such as parentheses.try using NSScanner
For Swift 3.0.1 folks
Output:
"13659918899"
This also trim spaces from string
Easily done by creating a character set of characters you want to keep and using
invertedSet
to create an "all others" set. Then split the string into an array separated by any characters in this set and reassemble the string again. Sounds complicated but very simple to implement:result:
333 9599 99