正则表达式的使用

Posted FOREVER IS NOW !

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了正则表达式的使用相关的知识,希望对你有一定的参考价值。

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

-(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 对错误密码进行查找,然后告诉用户非法密码(注册设置用户密码使用)

注意:

在使用手机号的正则的时候,需要及时的关注,移动、联通、电信等运营商是否新增加了手机号段。以免手持新增网段的用户在注册的时候,输入正确手机号,怎么也不能注册,导致用户被流失掉的问题发生。

个人在做这一块的时候,突然意识到这个问题,期望各大运营商能够为外界提供一个查询网段的API,这样我们的正则验证就能拿到最新的规则。但是非常的遗憾,我没有发现这样的API,如果有了这个API,其实也不好,该API的持有者,会根据请求的来源知晓你的App有那些用户,从另一个角度来说,对数据的安全也不是很好。想来想去,我们还是即时的关注主流运营商对号段的更新,但是客户端不能做到及时更新,或者说每次更新都要重新去审核,如果安卓端的多渠道打包上传,加在一起时非常的费时间的,综合了一下,还是不要去做手机号合法性的验证,但是简单的验证是必须的。

不知道,看到这里的猿友们,有没有什么更好的见解,请分享给我(直接写在评论里,我就能看到,谢谢)。

以上是关于正则表达式的使用的主要内容,如果未能解决你的问题,请参考以下文章

循环通过 python 正则表达式匹配

text 正则表达式片段

markdown 正则表达式模式片段

正则表达式匹配特定的 URL 片段而不是所有其他 URL 可能性

攻破难啃的骨头-正则表达式(转)

JavaScript中 正则表达式的使用 及 常用正则表达式