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:11

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]]];
        }
    }
}
查看更多
一夜七次
3楼-- · 2020-03-08 09:13
// 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.

查看更多
\"骚年 ilove
4楼-- · 2020-03-08 09:19

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"
查看更多
【Aperson】
5楼-- · 2020-03-08 09:25
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:@""];
}
查看更多
forever°为你锁心
6楼-- · 2020-03-08 09:29

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

查看更多
【Aperson】
7楼-- · 2020-03-08 09:31

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

查看更多
登录 后发表回答