Objective-C正则表达式检查电话号码 [英] Objective-c regex to check phone number
问题描述
可能重复:
用于电话号码验证的综合正则表达式
Possible Duplicate:
A comprehensive regex for phone number validation
如何在Objective-C中验证电话号码(NSString *)?规则:
How to validate a phone number (NSString *) in objective-c? Rules:
- 最少7位数字
- 最多10位数字
- 第一位数字必须为2、3、5、6、8或9
谢谢
推荐答案
您可以使用正则表达式库(例如RegexKit等),也可以通过NSPredicate
使用正则表达式(有点晦涩,但不能)需要第三方库).看起来像这样:
You can use a regular expressions library (like RegexKit, etc), or you could use regular expressions through NSPredicate
(a bit more obscure, but doesn't require third-party libraries). That would look something like this:
NSString *phoneNumber = ...;
NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
如果您使用的是iPhone,则iOS 4引入了NSRegularExpression
,该功能也可以使用. NSPredicate
方法适用于Mac和iPhone(任何版本).
If you're on iPhone, then iOS 4 introduced NSRegularExpression
, which would also work. The NSPredicate
approach works on both Mac and iPhone (any version).
这篇关于Objective-C正则表达式检查电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!