开发者

How to apply regex and/or clean a telephone string?

开发者 https://www.devze.com 2023-03-13 00:57 出处:网络
I have a NSString that contains fax telephone numbers. Sometimes I get different 开发者_C百科formats entered for example: (877) xxx-xxxx or 877-xxx-xxxx.

I have a NSString that contains fax telephone numbers. Sometimes I get different 开发者_C百科formats entered for example: (877) xxx-xxxx or 877-xxx-xxxx.

How do I get about cleaning the NSSString so that all I get is XXXxxxxxx.

Thanks


Using NSCharacterSet and NSMutableCharacterSet you can solve this problem in two ways.

  1. If you already know the characters that you want to remove.

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+-(),. "];
    NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
    NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
    
  2. If you don't know the characters, you can use the different character sets available already

    NSMutableCharacterSet *charSet = [NSMutableCharacterSet new];
    [charSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
    [charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
    [charSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
    NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
    NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
    
0

精彩评论

暂无评论...
验证码 换一张
取 消