ohh*_*hho 18 regex cocoa-touch objective-c
可能重复:
用于电话号码验证的全面正则表达式
如何在objective-c中验证电话号码(NSString*)?规则:
谢谢
Dav*_*ong 35
您可以使用正则表达式库(如RegexKit等),也可以使用正则表达式NSPredicate(稍微模糊一些,但不需要第三方库).这看起来像这样:
NSString *phoneNumber = ...;
NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
Run Code Online (Sandbox Code Playgroud)
如果您使用的是iPhone,那么iOS 4 NSRegularExpression将会推出,这也适用.该NSPredicate方法适用于Mac和iPhone(任何版本).
Raf*_*hes 11
对于那些搜索电话提取的人,您可以从文本中提取电话号码,例如:
NSString *userBody = @"This is a text with 30612312232 my phone";
if (userBody != nil) {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSArray *matches = [detector matchesInString:userBody options:0 range:NSMakeRange(0, [userBody length])];
if (matches != nil) {
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
DbgLog(@"Found phone number %@", [match phoneNumber]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
`