正则表达式检验邮箱地址与手机号

前端之家收集整理的这篇文章主要介绍了正则表达式检验邮箱地址与手机号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面给出两种不同的方法验证邮箱输入合法性

//通过区分字符串

-(BOOL)validateEmail:(NSString*)email

{

if((0 != [email rangeOfString:@"@"].length) &&

(0 != [email rangeOfString:@"."].length))

{

NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

NSMutableCharacterSet* tmpInvalidMutableCharSet = [[tmpInvalidCharSet mutableCopy] autorelease];

[tmpInvalidMutableCharSet removeCharactersInString:@"_-"];

/*
*使用compare option 来设定比较规则,如

*NSCaseInsensitiveSearch是不区分大小写

*NSLiteralSearch 进行完全比较,区分大小写

*NSNumericSearch 只比较定符串的个数,而不比较字符串的字面值
*/

NSRange range1 = [email rangeOfString:@"@" options:NSCaseInsensitiveSearch];

//取得用户名部分

NSString* userNameString = [email substringToIndex:range1.location];

NSArray* userNameArray = [userNameString componentsSeparatedByString:@"."];

for(NSString* string in userNameArray)

{

NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet: tmpInvalidMutableCharSet];

if(rangeOfInavlidChars.length != 0 || [string isEqualToString:@""])

return NO;

}

//取得域名部分

NSString *domainString = [email substringFromIndex:range1.location+1];

NSArray *domainArray = [domainString componentsSeparatedByString:@"."];

for(NSString *string in domainArray)

{

NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];

if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])

return NO;

}

return YES;

}

else {

return NO;

}

}

//利用正则表达式验证

-(BOOL)isValidateEmail:(NSString *)email {

NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];

return [emailTest evaluateWithObject:email];

}


手机号码验证:

-(BOOL)validateMobile(NSString* mobile) {

//手机号以13,15,18开头,八个 \d 数字字符
NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];

NSLog(@"phoneTest is %@",phoneTest);
return [phoneTest evaluateWithObject:mobile];
}

猜你在找的正则表达式相关文章