標籤:
Regex判斷手機號碼和電話號碼的方法:
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,18610 * 電信:133,1349,153,180,18911 */12 NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\d{8}$";13 /**14 * 中國移動:China Mobile15 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,18816 */17 NSString *CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\d)\d{7}$";18 /**19 * 中國聯通:China Unicom20 * 130,131,132,152,155,156,185,18621 */22 NSString *CU = @"^1(3[0-2]|5[256]|8[56])\d{8}$";23 /**24 * 中國電信:China Telecom25 * 133,1349,153,180,18926 */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,02931 * 號碼:七位或八位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 }
Regex判斷姓名(只允許包含中文或英文字母,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 }
Objective-C文法之NSPredicate的使用