问题:
随着项目越来越多,使用正则表达式的次数也越来越多了,之前只要写一次就搞定,现在因为有多个数据要判断和检测,所以最好封装好一个正则表达式的类,方便以后使用。问题是:现在需求是:如何使用正则表达式来判断密码、身份证、手机号码、邮箱等等之类的?
解决方法:
以下是利用正则表达式来判断用户密码是否匹配要求的,明天再继续更新我在项目中经常使用的正则表达
//FuPredicate.h
#import
@interfaceFuPredicate :NSObject
#pragma正则匹配用户密码6-16位数字和字母的组合
+ (BOOL)checkPassword:(NSString*)password;
#pragma正则匹配充值金额为非零的正整数
+ (BOOL)checkMoneyValue:(NSString*)money;
#pragma正则匹配Email
+ (BOOL)checkEmail:(NSString*)email;
#pragma正则匹配手机号
+ (BOOL)checkPhoneNo:(NSString*)PhoneNo;
#pragma正则匹配用户身份证号15或18位
+ (BOOL)checkIDCard: (NSString*)idCard;
#pragma正则匹配URL
+ (BOOL)checkURL : (NSString*) url;
@end
//FuPredicate.m
#import"FuPredicate.h"
@implementationFuPredicate
+(BOOL)checkPassword:(NSString*)password
{
NSString* pattern =@"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",pattern];
BOOL isMatch = [predicate evaluateWithObject:password];
return isMatch;
}
+ (BOOL)checkMoneyValue:(NSString*)money
{
NSString* pattern =@"^[1-9][0-9]*$";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",pattern];
BOOL isMatch = [predicate evaluateWithObject:money];
return isMatch;
}
+ (BOOL)checkEmail:(NSString*)email
{
NSString* pattern =@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",pattern];
BOOL isMatch = [predicate evaluateWithObject:email];
return isMatch;
}
+ (BOOL)checkPhoneNo:(NSString*)PhoneNo
{
NSString* pattern =@"^1[345678]\\d{9}$";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [predicate evaluateWithObject:PhoneNo];
return isMatch;
}
+ (BOOL)checkIDCard:(NSString*)idCard
{
NSString* pattern =@"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [predicate evaluateWithObject:idCard];
return isMatch;
}
+ (BOOL)checkURL:(NSString*)url
{
NSString* pattern =@"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
NSPredicate* predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [predicate evaluateWithObject:url];
return isMatch;
}
@end
总结:
我现在也还没有去看正则表达式,但是找到一篇不错的学习文章,跟大家一起学习一下。如果有更好的希望大家一起学习交流。
55分钟学会正则表达式(译)