-->

Remove all non-numeric characters from an NSString

2020-03-08 08:53发布

问题:

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?

回答1:

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:@""];

result: 333 9599 99



回答2:

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"


回答3:

// 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.



回答4:

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



回答5:

try using 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"


回答6:

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:@""];
}


回答7:

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