从NSString中删除所有非数字字符,保留空格

时间:2014-02-08 23:27:56

标签: ios objective-c string cocoa-touch nsstring

我正在尝试从NSString中删除所有非数字字符,但我还需要保留空格。这是我一直在使用的。

NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];

如果我给它一个Test 333 9599 999的NSString它将返回3339599999但我需要保留空格。

我该怎么做?

7 个答案:

答案 0 :(得分:28)

通过创建要保留的字符集并使用invertedSet创建“所有其他”字符集轻松完成。然后将字符串拆分为由此集合中的任何字符分隔的数组,并再次重新组合字符串。听起来很复杂但很容易实现:

NSCharacterSet *setToRemove =   
    [NSCharacterSet characterSetWithCharactersInString:@"0123456789 "];
NSCharacterSet *setToKeep = [setToRemove invertedSet];

NSString *newString = 
        [[someString componentsSeparatedByCharactersInSet:setToKeep]
            componentsJoinedByString:@""];

结果:333 9599 99

答案 1 :(得分:20)

你可以改变你的第一个正则表达式,在9:

之后加一个空格

在swift:

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

虽然这留下了领先的空间,但您可以应用空白修剪来处理:

strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// strippedStr = "33 9599 999"

答案 2 :(得分:4)

// Our test string
NSString* _bbox = @"Test 333 9599 999";

// Remove everything except numeric digits and spaces
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:@"[^\\d ]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
// (Optional) Trim spaces on either end, but keep spaces in the middle
strippedBbox = [strippedBbox stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

// Print result
NSLog(@"%@", strippedBbox);

这会打印333 9599 999,我认为这就是你所追求的。它还会删除可能位于字符串中间的非数字字符,例如括号。

答案 3 :(得分:3)

对于Swift 3.0.1人员

var str = "1 3 6 .599.188-99 "
    str.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression, range: nil)

输出:"13659918899"

这也会修剪字符串

中的空格

答案 4 :(得分:2)

尝试使用NSScanner

NSString *originalString = @"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString 
    stringWithCapacity:originalString.length];

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet 
    characterSetWithCharactersInString:@"0123456789 "];

while ([scanner isAtEnd] == NO) {
    NSString *buffer;
    if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
        [strippedString appendString:buffer];
    } else {
        [scanner setScanLocation:([scanner scanLocation] + 1)];
    }
}

NSLog(@"%@", strippedString); // "123123123"

答案 5 :(得分:0)

NSMutableString strippedBbox = [_bbox mutableCopy];
NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:@"1234567890 "].invertedSet;

NSUInteger start = 0;
NSUInteger length = _bbox.length;

while(length > 0)
{
    NSRange range = [strippedBbox rangeOfCharacterFromSet:charSet options:0 range:NSMakeRange(start, length)];

    if(range.location == NSNotFound)
    {
        break;
    }

    start += (range.location + range.length);
    length -= range.length;

    [strippedBbox replaceCharactersInRange:range withString:@""];
}

答案 6 :(得分:0)

简而言之,您可以使用NSCharacterSet仅检查那些您感兴趣的字符,而忽略其余的字符。

- (void) stripper {

    NSString *inString = @"A1 B2 C3 D4";
    NSString *outString = @"";

    for (int i = 0; i < inString.length; i++) {

        if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:[inString characterAtIndex:i]] || [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[inString characterAtIndex:i]]) {

            outString = [outString stringByAppendingString:[NSString stringWithFormat:@"%c",[inString characterAtIndex:i]]];
        }
    }
}