1. 程式人生 > >正則表示式的一些運用

正則表示式的一些運用

1、手機號

//因為各個運營商開頭號碼不同,這裡只匹配11位是比較好的方法

- (BOOL)isValidPhoneNumber {
    NSString *regex = @"^[0-9]{11}";
    return [self isValidateByRegex:regex];
}

//或者精確點,但需要根據運營商更新

- (BOOL)wl_isMobileNumberClassification {
    /**
     * 手機號碼
     * 移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,1705
     * 聯通:130,131,132,152,155,156,185,186,1709
     * 電信:133,1349,153,180,189,1700
     */

    /**
     10         * 中國移動:China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,1705
     12      
     */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\\\d|705)\\\\d{7}$";
    /**
     15         * 中國聯通:China Unicom
     16         * 130,131,132,152,155,156,185,186,1709
     17        
     */
    NSString * CU = @"^1((3[0-2]|5[256]|8[56])\\\\d|709)\\\\d{7}$";
    /**
     20         * 中國電信:China Telecom
     21         * 133,1349,153,180,189,1700
     22         
     */
    NSString * CT = @"^1((33|53|8[09])\\\\d|349|700)\\\\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}$";

    if (([self isValidateByRegex:CM])
        || ([self isValidateByRegex:CU])
        || ([self isValidateByRegex:CT])
        || ([self isValidateByRegex:PHS])) {
        return YES;
    }else {
        return NO;
    }
}

2、郵箱的有效性驗證

- (BOOL)isValidUrl {
    NSString * regex = @"\\\\b((ftp|http|https?):\\\\/\\\\/[-\\\\w]+(\\\\.\\\\w[-\\\\w]*)+|(?i:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\\\\.)+(?-i:com\\\\b|edu\\\\b|biz\\\\b|gov\\\\b|in(?:t|fo)\\\\b|mil\\\\b|net\\\\b|org\\\\b|[a-z][a-z]\\\\b))(:\\\\d+)?(/[^.!,?;\\"'<>()\\\\[\\\\]{}\\\\s\\\\x7F-\\\\xFF]*(?:[.!,?]+[^.!,?;\\"'<>()\\\\[\\\\]{}\\\\s\\\\x7F-\\\\xFF]+)*)?";
    return [self isValidateByRegex:regex];
}

3、簡單的身份證有效性

- (BOOL)simpleVerifyIdentityCardNum {
    NSString *regex2 = @"^(\\\\d{14}|\\\\d{17})(\\\\d|[xX])$";
    return [self isValidateByRegex:regex2];
}

4、車型

- (BOOL)validateCarType {
    NSString *regex2 = @"^[\\u4E00-\\u9FFF]+$";
    return [self isValidateByRegex:regex2];
}

5、判斷是否有特殊符號

- (BOOL)effectivePassWord {
    NSString *regex2 = @"[a-zA-Z0-9]{6,20};
    return [self isValidateByRegex:regex2];
}

6、密碼是否有效

- (BOOL)isValidPassword {
    //以字母開頭,只能包含“字母”,“數字”,“下劃線”,長度6~18
    NSString *regex = @"^([a-zA-Z]|[a-zA-Z0-9_]|[0-9]){6,18}$";
    return [self isValidateByRegex:regex];
}

7、車牌號的有效性驗證

- (BOOL)isCarNumber {
    //車牌號:湘K-DE829 香港車牌號碼:粵Z-J499港
    NSString *carRegex = @"^[\\u4e00-\\u9fff]{1}[a-zA-Z]{1}[-][a-zA-Z_0-9]{4}[a-zA-Z_0-9_\\u4e00-\\u9fff]$";//其中\\u4e00-\\u9fa5表示unicode編碼中漢字已編碼部分,\\u9fa5-\\u9fff是保留部分,將來可能會新增
    return [self isValidateByRegex:carRegex];
}

8、ip地址有效性

- (BOOL)isIPAddress {
    NSString *regex = [NSString stringWithFormat:@"^(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})$"];
    BOOL rc = [self isValidateByRegex:regex];

    if (rc) {
        NSArray *componds = [self componentsSeparatedByString:@","];

        BOOL v = YES;
        for (NSString *s in componds) {
            if (s.integerValue > 255) {
                v = NO;
                break;
            }
        }

        return v;
    }

    return NO;
}

9、Mac地址有效性

- (BOOL)isMacAddress {
    NSString * macAddRegex = @"([A-Fa-f\\\\d]{2}:){5}[A-Fa-f\\\\d]{2}";
    return  [self isValidateByRegex:macAddRegex];
}

10、是否純漢字

- (BOOL)isValidChinese {
    NSString *chineseRegex = @"^[\\u4e00-\\u9fa5]+$";
    return [self isValidateByRegex:chineseRegex];
}

11、是否郵政編碼

- (BOOL)isValidPostalcode {
    NSString *postalRegex = @"^[0-8]\\\\d{5}(?!\\\\d)$";
    return [self isValidateByRegex:postalRegex];
}

12、是否工商稅號

- (BOOL)isValidTaxNo {
    NSString *taxNoRegex = @"[0-9]\\\\d{13}([0-9]|X)$";
    return [self isValidateByRegex:taxNoRegex];
}

13、是否符合最小長度、最長長度,是否包含中文,首字母是否可以為數字

/**
 @brief     是否符合最小長度、最長長度,是否包含中文,首字母是否可以為數字
 @param     minLenth 賬號最小長度
 @param     maxLenth 賬號最長長度
 @param     containChinese 是否包含中文
 @param     firstCannotBeDigtal 首字母不能為數字
 @return    正則驗證成功返回YES, 否則返回NO
 */
- (BOOL)isValidWithMinLenth:(NSInteger)minLenth
                      maxLenth:(NSInteger)maxLenth
                containChinese:(BOOL)containChinese
           firstCannotBeDigtal:(BOOL)firstCannotBeDigtal;
{
    //  [\\u4e00-\\u9fa5A-Za-z0-9_]{4,20}
    NSString *hanzi = containChinese ? @"\\u4e00-\\u9fa5" : @"";
    NSString *first = firstCannotBeDigtal ? @"^[a-zA-Z_]" : @"";

    NSString *regex = [NSString stringWithFormat:@"%@[%@A-Za-z0-9_]{%d,%d}", first, hanzi, (int)(minLenth-1), (int)(maxLenth-1)];
    return [self isValidateByRegex:regex];
}

14、是否符合最小長度、最長長度,是否包含中文,數字,字母,其他字元,首字母是否可以為數字

/**
 @brief     是否符合最小長度、最長長度,是否包含中文,數字,字母,其他字元,首字母是否可以為數字
 @param     minLenth 賬號最小長度
 @param     maxLenth 賬號最長長度
 @param     containChinese 是否包含中文
 @param     containDigtal   包含數字
 @param     containLetter   包含字母
 @param     containOtherCharacter   其他字元
 @param     firstCannotBeDigtal 首字母不能為數字
 @return    正則驗證成功返回YES, 否則返回NO
 */
- (BOOL)isValidWithMinLenth:(NSInteger)minLenth
                      maxLenth:(NSInteger)maxLenth
                containChinese:(BOOL)containChinese
                 containDigtal:(BOOL)containDigtal
                 containLetter:(BOOL)containLetter
         containOtherCharacter:(NSString *)containOtherCharacter
           firstCannotBeDigtal:(BOOL)firstCannotBeDigtal;
{
    NSString *hanzi = containChinese ? @"\\u4e00-\\u9fa5" : @"";
    NSString *first = firstCannotBeDigtal ? @"^[a-zA-Z_]" : @"";
    NSString *lengthRegex = [NSString stringWithFormat:@"(?=^.{%@,%@}$)", @(minLenth), @(maxLenth)];
    NSString *digtalRegex = containDigtal ? @"(?=(.*\\\\d.*){1})" : @"";
    NSString *letterRegex = containLetter ? @"(?=(.*[a-zA-Z].*){1})" : @"";
    NSString *characterRegex = [NSString stringWithFormat:@"(?:%@[%@A-Za-z0-9%@]+)", first, hanzi, containOtherCharacter ? containOtherCharacter : @""];
    NSString *regex = [NSString stringWithFormat:@"%@%@%@%@", lengthRegex, digtalRegex, letterRegex, characterRegex];
    return [self isValidateByRegex:regex];
}

15、匹配正則表示式的一些簡單封裝

- (BOOL)isValidateByRegex:(NSString *)regex {
    NSPRedicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:self];
}
/**
 是否能夠匹配正則表示式

 @param regex  正則表示式
 @param options     普配方式.
 @return YES:如果可以匹配正則表示式; 否則,NO.
 */
- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options {
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:NULL];
    if (!pattern) return NO;
    return ([pattern numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)] > 0);
}
/**
 匹配正則表示式,並使用匹配的每個物件執行給定的塊。

 @param regex    正則表示式
 @param options  上報的匹配選項.
 @param block    應用於在陣列元素中匹配的塊.
 該塊需要四個引數:
 match: 匹配的子串.
 matchRange: 匹配選項.
 stop: 一個布林值的引用。塊可以設定YES來停止處理陣列。stop引數是一個唯一的輸出。你應該給塊設定YES。
 */
- (void)enumerateRegexMatches:(NSString *)regex
                         options:(NSRegularExpressionOptions)options
                      usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block {
    if (regex.length == 0 || !block) return;
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!regex) return;
    [pattern enumerateMatchesInString:self options:kNilOptions range:NSMakeRange(0, self.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        block([self substringWithRange:result.range], result.range, stop);
    }];
}

/**
 返回一個包含匹配正則表示式的新字串替換為模版字串。

 @param regex       正則表示式
 @param options     上報的匹配選項.
 @param replacement 用來替換匹配到的內容.

 @return 返回一個用指定字串替換匹配字串後的字串.
 */
- (NSString *)stringByReplacingRegex:(NSString *)regex
                                options:(NSRegularExpressionOptions)options
                             withString:(NSString *)replacement {
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!pattern) return self;
    return [pattern stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:replacement];
}

16、另外提供兩個常用演算法

1)精確的身份證號碼有效性檢測

+ (BOOL)accurateVerifyIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    int length =0;
    if (!value) {
        return NO;
    }else {
        length = (int)value.length;

        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份程式碼
    NSArray *areasArray [email protected][@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];

    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }

    if (!areaFlag) {
        return false;
    }

    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;

    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;

            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {

                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//測試出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//測試出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];

            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {

                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//測試出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//測試出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];

            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M [email protected]"F";
                NSString *JYM [email protected]"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判斷校驗位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 檢測ID的校驗位
                }else {
                    return NO;
                }

            }else {
                return NO;
            }
        default:
            return NO;
    }
}

2)銀行卡號有效性問題Luhn演算法

/** 銀行卡號有效性問題Luhn演算法
 *  現行 16 位銀聯卡現行卡號開頭 6 位是 622126~622925 之間的,7 到 15 位是銀行自定義的,
 *  可能是髮卡分行,髮卡網點,髮卡序號,第 16 位是校驗碼。
 *  16 位卡號校驗位採用 Luhm 校驗方法計算:
 *  1,將未帶校驗位的 15 位卡號從右依次編號 1 到 15,位於奇數位號上的數字乘以 2
 *  2,將奇位乘積的個十位全部相加,再加上所有偶數位上的數字
 *  3,將加法和加上校驗位能被 10 整除。
 */
- (BOOL)wl_bankCardluhmCheck{
    NSString * lastNum = [[self substringFromIndex:(self.length-1)] copy];//取出最後一位
    NSString * forwardNum = [[self substringToIndex:(self.length -1)] copy];//前15或18位

    NSMutableArray * forwardArr = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i=0; i<forwardNum.length; i++) {
        NSString * subStr = [forwardNum substringWithRange:NSMakeRange(i, 1)];
        [forwardArr addObject:subStr];
    }

    NSMutableArray * forwardDescArr = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = (int)(forwardArr.count-1); i> -1; i--) {//前15位或者前18位倒序存進陣列
        [forwardDescArr addObject:forwardArr[i]];
    }

    NSMutableArray * arrOddNum = [[NSMutableArray alloc] initWithCapacity:0];//奇數位*2的積 < 9
    NSMutableArray * arrOddNum2 = [[NSMutableArray alloc] initWithCapacity:0];//奇數位*2的積 > 9
    NSMutableArray * arrEvenNum = [[NSMutableArray alloc] initWithCapacity:0];//偶數位陣列

    for (int i=0; i< forwardDescArr.count; i++) {
        NSInteger num = [forwardDescArr[i] intValue];
        if (i%2) {//偶數位
            [arrEvenNum addObject:[NSNumber numberWithInteger:num]];
        }else{//奇數位
            if (num * 2 < 9) {
                [arrOddNum addObject:[NSNumber numberWithInteger:num * 2]];
            }else{
                NSInteger decadeNum = (num * 2) / 10;
                NSInteger unitNum = (num * 2) % 10;
                [arrOddNum2 addObject:[NSNumber numberWithInteger:unitNum]];
                [arrOddNum2 addObject:[NSNumber numberWithInteger:decadeNum]];
            }
        }
    }

    __block  NSInteger sumOddNumTotal = 0;
    [arrOddNum enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL *stop) {
        sumOddNumTotal += [obj integerValue];
    }];

    __block NSInteger sumOddNum2Total = 0;
    [arrOddNum2 enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL *stop) {
        sumOddNum2Total += [obj integerValue];
    }];

    __block NSInteger sumEvenNumTotal =0 ;
    [arrEvenNum enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL *stop) {
        sumEvenNumTotal += [obj integerValue];
    }];

    NSInteger lastNumber = [lastNum integerValue];

    NSInteger luhmTotal = lastNumber + sumEvenNumTotal + sumOddNum2Total + sumOddNumTotal;

    return (luhmTotal%10 ==0)?YES:NO;
}