Remove all non-numeric characters from an NSString

2020-03-08 08:30发布

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?

7条回答
乱世女痞
2楼-- · 2020-03-08 09:36

You could alter your first regex to include a space after the 9:

In swift:

var str = "test Test 333 9599 999";
val strippedStr = str.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
// strippedStr = " 33 9599 999"

While this leaves the leading space, you could apply a whitespace trimming to deal with that:

strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// strippedStr = "33 9599 999"
查看更多
登录 后发表回答