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

前端 未结 7 650
野性不改
野性不改 2021-01-07 21:57

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.

NS         


        
相关标签:
7条回答
  • 2021-01-07 22:54
    // 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.

    0 讨论(0)
提交回复
热议问题