绝大多数注册类应用都会选择使用手机号作为用户的注册的账号,由于键盘上有限的字符基本都是常用的手动输入的手机号的合法性比较容易控制.但是如果用户选择粘贴的复制的方式就会混进来一些特殊的字符造成判断上的异常.
在自带系统是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);