从NSString中删除所有非数字字符,保留空格 [英] Remove all non-numeric characters from an NSString, keeping spaces
问题描述
我想从 NSString
中删除所有的非数字字符,但我也需要保留空格。这是我一直在使用的。
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])];
如果我给它一个NSString Test 333 9599 999
它会返回 3339599999
,但我需要保留空格。
If I give it a NSString of Test 333 9599 999
It will return 3339599999
but I need to keep the spaces in.
我该如何做?
推荐答案
通过创建要保留的字符集并使用 invertedSet
创建一个所有其他集合。然后将该字符串拆分为由此集合中的任何字符分隔的数组,并重新组装该字符串。听起来很复杂但实现起来很简单:
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:
NSCharacterSet *setToRemove =
[NSCharacterSet characterSetWithCharactersInString:@"0123456789 "];
NSCharacterSet *setToKeep = [setToRemove invertedSet];
NSString *newString =
[[someString componentsSeparatedByCharactersInSet:setToKeep]
componentsJoinedByString:@""];
结果: 333 9599 99
这篇关于从NSString中删除所有非数字字符,保留空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!