通訊錄中的特殊字符

絕大多數註冊類應用都會選擇使用手機號作爲用戶的註冊的賬號,由於鍵盤上有限的字符基本都是常用的手動輸入的手機號的合法性比較容易控制.但是如果用戶選擇粘貼的複製的方式就會混進來一些特殊的字符造成判斷上的異常.

在自帶系統是iOS 11.0+的設備上覆制通話記錄中的手機號時,發現複製之後的手機號出了空格之外的部分並不是11位.

    UIPasteboard *sb = [UIPasteboard generalPasteboard];
    NSString *content = [sb.string stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"length == %@", @(content.length));
    char charAtGivenIndex;
    for (int index = 0; index < content.length; index++) {
        charAtGivenIndex = [content characterAtIndex:index];
        NSLog(@"%c", charAtGivenIndex);
    }

輸出結果:

 length == 13
 -
 1
 8
 4
 1
 3
 4
 8
 0
 4
 4
 8
 ,

在字符的首尾多出了非數字非空格的字符,如果使用只識別數字和空格的正則表達式來匹配時就會出現結果不匹配的情況,從而導致異常.

那麼如何處理非法字符呢?

在字符串的處理中已經提供了可用的方法,常用的有以下兩種:

  • 使用非法字符分割字符串得到合法字符串的數組,然後再對合法字符串數組進行拼接.
    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]; //除數字之外的其他字符均爲非法字符,使用invertedSet方法進行字符集反轉
    NSArray<NSString *> *allElements = [content componentsSeparatedByCharactersInSet:characterSet]; //使用非法字符的字符集分割原始字符串得到合法字符(串)數組
    NSString *result = [allElements componentsJoinedByString:@""]; //使用空字符拼接合法字符串數組得到合法字符組成的字符串
    NSLog(@"result == %@", result);
  • 由於在給出的實例中不合法字符出現在字符串的首尾位置,所以可以使用字符串提供的去除字符串首尾不合法字符的方法
    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789 "] invertedSet]; //使用字符集invertedSet方法反轉字符集
    NSString *result =  [content stringByTrimmingCharactersInSet:characterSet]; //去除字符串首尾的不合法字符
    NSLog(@"result == %@", result);

這種現象在獲取設備通訊錄中聯繫人時也經常遇到.

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    
    NSArray<CNLabeledValue<CNPhoneNumber*>*> *phoneNumbers = contact.phoneNumbers;
    for (CNLabeledValue<CNPhoneNumber*>* value in phoneNumbers) {
        NSString *label = value.label;
        NSLog(@"label == %@", label);
        //此處輸出的結果會出現類似_$!<Mobile>!$_這種形式,而事實上只並不是需要的有效字符
        CNPhoneNumber *phoneNumber =  value.value;
        NSString *phone = phoneNumber.stringValue;
        NSLog(@"phone == %@", phone);
        
    }
}

輸出結果:

label == _$!<Mobile>!$_
phone == 18413480448

所以如果想要分離label中的有效字符串就可以同樣適用上邊的方法:
 

NSString *label = value.label;
label = [label stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"_$!<>"]];
NSLog(@"label == %@", label);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章