In xcode does anyone know how to check that a string is this kind of phone number (123) 456-7890?
I've tried this and it's not working:
range1 = NSMakeRange(0,[string length]);
NSRegularExpression *regex;
regex = [NSRegularExpression
regularExpressionWithPattern:@"([0-9]{开发者_JS百科3}) [0-9]{3}-[0-9]{4}"
options:0 error:NULL];
range2 = [regex rangeOfFirstMatchInString:string options:0 range:range1];
if (NSEqualRanges(range1, range2)) {
return YES;
}
// range2 always equals the "not found" range. // Thx
I think it should be '\\' (double slashes) and not '\' (single slash)..
- (BOOL) validatePhone: (NSString *) candidate {
NSString *phoneRegex = @"\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
return [phoneTest evaluateWithObject:candidate];
}
精彩评论