NSRegularExpression是iOS系统在4.0后自带的匹配正则表达式,一般会和NSTextCheckingResult配套使用。
代码:
//匹配输入的联系方式是否为QQ号码或者电子邮箱
NSString *patternQQ = @"^[1-9](\\d){4,9}$";NSString *patternEmail = @"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";
NSError *error = NULL;
//定义正则表达式
NSRegularExpression *regexQQ = [NSRegularExpression regularExpressionWithPattern:patternQQ options:0 error:&error];
NSRegularExpression *regexEmail = [NSRegularExpression regularExpressionWithPattern:patternEmail options:0 error:&error];
//使用正则表达式匹配字符
NSTextCheckingResult *isMatchQQ = [regexQQ firstMatchInString:textField.text
options:0
range:NSMakeRange(0, [textField.text length])];
NSTextCheckingResult *isMatchEmail = [regexEmail firstMatchInString:textField.text
options:0
range:NSMakeRange(0, [textField.text length])];
if (isMatchQQ || isMatchEmail) {
//doing thing
}