Objective-C语法之NSPredicate的使用

正则表达式判断手机号码和电话号码的方法:

 1 #import <Foundation/Foundation.h>
 2 /**
 3  正则判断手机号码地址格式
 4  */
 5 BOOL isMobileNumber(NSString *mobileNum) {
 6     /**
 7      * 手机号码
 8      * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
 9      * 联通:130,131,132,152,155,156,185,186
10      * 电信:133,1349,153,180,189
11      */
12     NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\d{8}$";
13     /**
14      * 中国移动:China Mobile
15      * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
16      */
17     NSString *CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\d)\d{7}$";
18     /**
19      * 中国联通:China Unicom
20      * 130,131,132,152,155,156,185,186
21      */
22     NSString *CU = @"^1(3[0-2]|5[256]|8[56])\d{8}$";
23     /**
24      * 中国电信:China Telecom
25      * 133,1349,153,180,189
26      */
27     NSString *CT = @"^1((33|53|8[09])[0-9]|349)\d{7}$";
28     /**
29      * 大陆地区固话及小灵通
30      * 区号:010,020,021,022,023,024,025,027,028,029
31      * 号码:七位或八位
32      */
33     // NSString *PHS = @"^0(10|2[0-5789]|\d{3})\d{7,8}$";
34     
35     NSPredicate *regexMOBILE = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
36     NSPredicate *regexCM = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
37     NSPredicate *regexCU = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
38     NSPredicate *regexCT = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
39     
40     BOOL isValid = [regexMOBILE evaluateWithObject:mobileNum]
41         || [regexCM evaluateWithObject:mobileNum]
42         || [regexCU evaluateWithObject:mobileNum]
43         || [regexCT evaluateWithObject:mobileNum];
44     return isValid;
45 }
46 int main(int argc, const char * argv[]) {
47     @autoreleasepool {
48         NSString *mobileNumber = @"13523424438";
49         BOOL isValid = isMobileNumber(mobileNumber);
50         NSLog(@"%@是否是有效的手机号码?%@", mobileNumber, isValid ? @"是":@"否"); //是
51         
52         mobileNumber = @"135234244ik";
53         isValid = isMobileNumber(mobileNumber);
54         NSLog(@"%@是否是有效的手机号码?%@", mobileNumber, isValid ? @"是":@"否"); //否
55         
56         mobileNumber = @"135234244456776";
57         isValid = isMobileNumber(mobileNumber);
58         NSLog(@"%@是否是有效的手机号码?%@", mobileNumber, isValid ? @"是":@"否"); //否
59     }
60     return 0;
61 }

正则表达式判断姓名(只允许包含中文或英文字母,10个字符以内)的方法:

1 + (BOOL)isValidateName:(NSString *)name {
2     NSString *nameRegex = @"^[\u4E00-\u9FA5A-Za-z]{1,10}";
3     NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
4     return [namePredicate evaluateWithObject:name];
5 }