OS中一共有3种方式进行正则表达式的匹配NSPredicate、NSRegularExpression、NSString
一、使用NSPredicate
void useNSPredicate() { NSString *phoneNO = @"13182428488"; NSString *regex = @"^1[3|4|5|7|8]\d{9}$"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isValid = [predicate evaluateWithObject:phoneNO]; NSLog(@"%s %d", __FUNCTION__ ,isValid); }
二、使用原生NSRegularExpression
void useNSRegularExpression() { NSString *phoneNO = @"13182428488"; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^1[3|4|5|7|8]\d{9}$" options:NSRegularExpressionCaseInsensitive error:&error]; NSTextCheckingResult *result = [regex firstMatchInString:phoneNO options:0 range:NSMakeRange(0, [phoneNO length])]; if (result) { NSRange resultRange = [result rangeAtIndex:0]; //从urlString中截取数据 NSString *stringResult = [phoneNO substringWithRange:resultRange]; NSLog(@"%s %@ ", __FUNCTION__, stringResult); } }
三、使用NSString
void useNSString() { NSString *phoneNO = @"13182428488"; NSRange range = [phoneNO rangeOfString:@"^1[3|4|5|7|8]\d{9}$" options:NSRegularExpressionSearch]; if (range.location != NSNotFound) { NSLog(@"%s %@ ", __FUNCTION__, [phoneNO substringWithRange:range]); } }