码迷,mamicode.com
首页 > 其他好文 > 详细

正则表达式的使用

时间:2016-05-20 21:05:04      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

参考一篇不错的博文:参考

技术分享
-(BOOL)isLoginPassWordLegal:(NSString *)passWord{
    BOOL result = false;
    if ([passWord length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:passWord];
    }
    return result;
}
View Code 判断登录名是否是数字、字母组成
技术分享
- (BOOL)isPhoneNoLegal:(NSString *)phoneNo
{
    if (nil == phoneNo) {
        return NO;
    }
    /* 手机号码
     * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通:130,131,132,152,155,156,185,186
     * 电信:133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";//增加了一个3
    /**
     10         * 中国移动:China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通:China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信:China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号:010,020,021,022,023,024,025,027,028,029
     27         * 号码:七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:phoneNo] == YES)
        || ([regextestcm evaluateWithObject:phoneNo] == YES)
        || ([regextestct evaluateWithObject:phoneNo] == YES)
        || ([regextestcu evaluateWithObject:phoneNo] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
View Code 判断手机号码是否合法
技术分享
- (id)receiveClassObjcParm1:(NSString *)className parm2:(NSString*)classID{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:className bundle:[NSBundle mainBundle]];
    Class myClass = NSClassFromString(className);
    UIViewController * tempController = [storyboard instantiateViewControllerWithIdentifier:classID];
    if ([tempController isKindOfClass:myClass]) {
        return tempController;
    }
    return nil;
    
}
View Code 辅助加载创建storyBoard 文件
技术分享
//这里延缓执行 0.3秒
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
      
    });
View Code 延缓执行代码块的方法
技术分享
//判断身份证号是否位数够 (YES 位数够  18 或 15 位)
-(BOOL)isIdCardNum:(NSString*)idCardNum{
    BOOL isOK = NO;
    if ( 15 == idCardNum.length ) {
        isOK = YES;
    }
    if ( 18 == idCardNum.length) {
        isOK = YES;
    }
    if (nil == idCardNum) {
        isOK = NO;
    }
    return isOK;
}
View Code 判断身份证是否合法的方法
技术分享
- (BOOL) checkCardNo:(NSString*) cardNo{
    int oddsum = 0;
    int evensum = 0;
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}
View Code 判断银行卡号是否合法的方法
技术分享
// 拼接请求
-(NSString *)postMessageWithCardType:(NSString *)type
                             nameStr:(NSString*)userName
                          cardNumStr:(NSString*)cardNum
                           idCardStr:(NSString*)idCard
                         phoneNumStr:(NSString*)phoneNum
                            safeCode:(NSString*)codeStr
                          effectTime:(NSString*)effectTimeStr
{
    NSString * mutlstr;
    if ([type isEqualToString:@"1"])//储蓄卡
    {
        
        mutlstr = [NSString stringWithFormat:@"{\"cardNo\":\"%@\",\"cardType\":\"1\",\"certifId\":\"%@\",\"certifTp\":\"01\",\"customerNm\":\"%@\",\"phoneNo\":\"%@\"}",cardNum,idCard,userName,phoneNum];
    }
    else
    {
        if (codeStr.length == 0 || effectTimeStr.length == 0)
        {
            return nil;
        }
        else
        {
            mutlstr = [NSString stringWithFormat:@"{\"cardNo\":\"%@\",\"cardType\":\"2\",\"certifId\":\"%@\",\"certifTp\":\"01\",\"customerNm\":\"%@\",\"cvn2\":\"%@\",\"expired\":\"%@\",\"phoneNo\":\"%@\"}",cardNum,idCard,userName,codeStr,effectTimeStr,phoneNum];
        }
    }
    
    return mutlstr;
}
View Code 拼接请求字符串的方法
技术分享
#import <Foundation/Foundation.h>

@implementation NSDictionary (Log)
- (NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *str = [NSMutableString string];
    
    [str appendString:@"{\n"];
    
    // 遍历字典的所有键值对
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [str appendFormat:@"\t%@ = %@,\n", key, obj];
    }];
    
    [str appendString:@"}"];
    
    // 查出最后一个,的范围
    NSRange range = [str rangeOfString:@"," options:NSBackwardsSearch];
    if (range.length != 0) {
        // 删掉最后一个,
        [str deleteCharactersInRange:range];
    }
    
    return str;
}
@end

@implementation NSArray (Log)
- (NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *str = [NSMutableString string];
    
    [str appendString:@"[\n"];
    
    // 遍历数组的所有元素
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [str appendFormat:@"%@,\n", obj];
    }];
    
    [str appendString:@"]"];
    
    // 查出最后一个,的范围
    NSRange range = [str rangeOfString:@"," options:NSBackwardsSearch];
    if (range.length != 0) {
        // 删掉最后一个,
        [str deleteCharactersInRange:range];
    }
    
    return str;
}
@end
View Code Foundation+Log.m 文件方便请求网络后对数据的打印(解决汉字是编码的问题)
技术分享
///获得时间
+(NSString *)gmAcquireNowTime{
    //得到当前时间
    NSDate *timeNow = [NSDate date];
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"YYYY-MM-dd"];//得到年月日
    NSString *strDate = [dateFormater stringFromDate:timeNow];
    //    NSLog(@"%@",strDate);
    
    //得到年月日,时分秒
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:timeNow];
    //    NSString *timeCur = [NSString stringWithFormat:@"%d-%d-%d %02d:%02d:%02d",[components year],[components month],[components day],[components hour],[components minute],[components second]];
    NSString *timeCur = [NSString stringWithFormat:@"%@ %02ld:%02ld:%02ld",strDate,(long)[components hour],(long)[components minute],(long)[components second]];
    //    NSLog(@"%@",timeCur);
    
    return timeCur;
}
View Code 获取时间格式为 2016-04-21 19:53:23 的方法
技术分享
+ (BOOL)validateEmail:(NSString *)str2validate  
{  
    NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
    NSPredicate *emailPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];  
      
    return [emailPredicate evaluateWithObject:str2validate];  
}
View Code 对邮箱格式的检查方法
技术分享
//判断密码(6-16位数字、字母、特殊符合集三者组合)特殊字符集是{ []{}#%^*+=_\|~<>€£¥•.,?!‘-/:;()$&@" }
-(BOOL)judgePsword:(NSString*)passWord{
    BOOL result = false;
    if ([passWord length] >= 6){
        // 判断长度大于6位后再接着判断是否包含数字、字母、特殊字符(三者之间是或关系)
        //NSString * regex = @"^(?![0-9]+$)|(?![a-zA-Z]+$)|[0-9A-Za-z-\\[\\]~`€£¥•!@#$%^&*()_+=|}{:;‘/?<>,.\"\\\\]{6,16}$";//包括欧元人民币符号等ASCII没有的符号,但是iPhone键盘里有的
        //下面是按照标准的ASCII符号特殊字符集(保证任何手机都有)
        NSString * regex = @"^(?![0-9]+$)|(?![a-zA-Z]+$)|[0-9A-Za-z-\\[\\]~`€£¥•!@#$%^&*()_+=|}{:;‘/?<>,.\"\\\\]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:passWord];
    }
    NSMutableArray *unSafeStr = [NSMutableArray array];
    if (!result) {
        //如果某一个不存在的话,单独调处来
        for(int i =0; i < [passWord length]; i++)
        {
          NSString *temp = [passWord substringWithRange:NSMakeRange(i, 1)];
            BOOL isOk;
            NSString * regex = @"^(?![0-9]+$)|(?![a-zA-Z]+$)|[0-9A-Za-z-\\[\\]~`€£¥•!@#$%^&*()_+=|}{:;‘/?<>,.\"\\\\]{1,16}$";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            isOk = [pred evaluateWithObject:temp];
            if (!isOk) {
                [unSafeStr addObject:temp];
                NSLog(@"找到的错误是%@",unSafeStr
                      );
            }
        }
    }
    if (0!=unSafeStr.count) {
        NSString *tishi = @"检测密码不能包含非法字符:";
        for (int i = 0; i<unSafeStr.count; i++) {
           NSString *temp = unSafeStr[i];
           temp =  [temp stringByAppendingString:@""];
           tishi = [tishi stringByAppendingString:temp];
        }
        tishi = [tishi substringWithRange:NSMakeRange(0, tishi.length - 1)];
        //全局的提示框提示内容
        NSLog(@"————————————%@",tishi);
    }
    
    return result;
}
View Code 对错误密码进行查找,然后告诉用户非法密码(注册设置用户密码使用)

 

正则表达式的使用

标签:

原文地址:http://www.cnblogs.com/benpaobadaniu/p/5418410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!