Remove all non-numeric characters from an NSString, keeping spaces

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.

  • NSData from hex String?
  • Swift: Check String if it has an element in an Array
  • How to know if two emojis will be displayed as one emoji?
  • swift - Convert a String to a Date and then to a String in a different format
  • How to know the displayed text in UILabel?
  • How to split a string into substrings of equal length
  • How can I do this?

    7 Solutions Collect From Internet About “Remove all non-numeric characters from an NSString, keeping spaces”

    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]

    result: 333 9599 99

    In 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 = "33 9599 999"
    // 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);

    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.

    For Swift 3.0.1 folks

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

    Output: "13659918899"

    This also trim spaces from string

    try using NSScanner

    NSString *originalString = @"(123) 123123 abc";
    NSMutableString *strippedString = [NSMutableString 
    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"
    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)
        start += (range.location + range.length);
        length -= range.length;
        [strippedBbox replaceCharactersInRange:range withString:@""];

    In brief, you can use NSCharacterSet to examine only those chars that are interesting to you and ignore the rest.

    - (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]]];