iOS常用正則表達式

摘自http://blog.csdn.net/xlawszero/article/details/52053184
舊的正則表達式代碼:

  • (BOOL)isMobileNumber:(NSString )mobileNum
    {
    /
    *

    • 手機號碼
    • 移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,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[025-9])\d{8}$";
      /
      *
      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:mobileNum] == YES)
    || ([regextestcm evaluateWithObject:mobileNum] == YES)
    || ([regextestct evaluateWithObject:mobileNum] == YES)
    || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
    return YES;
    }
    else
    {
    return NO;
    }
    }

新版正則表達式代碼:

  • (BOOL)isMobileNumber:(NSString )mobileNum
    {
    if (mobileNum.length != 11)
    {
    return NO;
    }
    /
    *
    • 手機號碼:
    • 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
    • 移動號段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
    • 聯通號段: 130,131,132,155,156,185,186,145,176,1709
    • 電信號段: 133,153,180,181,189,177,1700
      /
      NSString MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\d{8}$";
      /
    • 中國移動:China Mobile
    • 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
      /
      NSString CM = @"(1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(1705\d{7}$)";
      /
    • 中國聯通:China Unicom
    • 130,131,132,155,156,185,186,145,176,1709
      /
      NSString CU = @"(1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(1709\d{7}$)";
      /
    • 中國電信:China Telecom
    • 133,153,180,181,189,177,1700
      */
      NSString *CT = @"(1(33|53|77|8[019])\d{8}$)|(1700\d{7}$)";
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:mobileNum] == YES)
    || ([regextestcm evaluateWithObject:mobileNum] == YES)
    || ([regextestct evaluateWithObject:mobileNum] == YES)
    || ([regextestcu evaluateWithObject:mobileNum] == YES))
{
    return YES;
}
else
{
    return NO;
}

}

下面我們簡單拆分上面方法,來應對不同的需求

如果只是簡單匹配是否是 手機號碼,并不需要上面那么多行代碼,可以簡單寫成這樣:

NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:mobileNum];

如果你需要匹配是否是 移動/聯通/電信 手機號。
判斷移動手機號就是這樣:

  • (BOOL)isChinaMobile:(NSString *)phoneNum
    {
    NSString *CM = @"(1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(1705\d{7}$)";
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    return [regextestcm evaluateWithObject:phoneNum];
    }

相信細心的朋友,應該已經明白了。判斷聯通手機號,只要把我們的正則字符串改成上面判斷聯通手機號的字符串就可以了。判斷哪種就改變正則表達式就可以了

ok,在這個基礎上,我們還可以組合來判斷具體是哪個運營商的手機號,代碼如下:

  • (NSString *)getPhoneNumType:(NSString *)phoneNum
    {
    return [self isChinaMobile:phoneNum]? @"中國移動": ([self isChinaUnicom:phoneNum]? @"中國聯通":([self isChinaTelecom:phoneNum]? @"中國電信": @"未知"));
    }

主要方法都已公布,至于Swift或者其他語言代碼塊就不一一放上來了,真讓我都寫,我也不一定都會。。。哈哈哈,核心正則表達式,都是可以用的,拿著代入進去就ok了。

摘自:http://www.cnblogs.com/littlesnail/p/6049705.html

import "NSString+RegexCategory.h"

@implementation NSString (RegexCategory)

pragma mark - 正則相關

  • (BOOL)isValidateByRegex:(NSString *)regex{
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:self];
    }

pragma mark -

//手機號分服務商

  • (BOOL)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
      */
      // NSString * MOBILE = @"^1((3//d|5[0-35-9]|8[025-9])//d|70[059])\d{7}$";//總況

    /**
    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}$";


//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

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

}

//手機號有效性

  • (BOOL)isMobileNumber{
    /**

    • 手機號以13、15、18、170開頭,8個 \d 數字字符
    • 小靈通 區號:010,020,021,022,023,024,025,027,028,029 還有未設置的新區號xxx
      */
      NSString *mobileNoRegex = @"1((3\d|5[0-35-9]|8[025-9])\d|70[059])\d{7}$";//除4以外的所有個位整數,不能使用[4,\d]匹配,這里是否iOS Bug?
      NSString *phsRegex =@"^0(10|2[0-57-9]|\d{3})\d{7,8}$";

    BOOL ret = [self isValidateByRegex:mobileNoRegex];
    BOOL ret1 = [self isValidateByRegex:phsRegex];

    return (ret || ret1);
    }

//郵箱

  • (BOOL)isEmailAddress{
    NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
    return [self isValidateByRegex:emailRegex];
    }

//身份證號

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

//車牌

  • (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];
    }

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

  • (BOOL)isValidUrl
    {
    NSString regex = @"((http)|(https))+:[\s]+\.[^\s]$";
    return [self isValidateByRegex:regex];
    }

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

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

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

  • (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];
    }

  • (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];
    }

pragma mark - 算法相關

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

  • (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 =@[@"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 =@"F";
            NSString *JYM =@"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;
}

}

/** 銀行卡號有效性問題Luhn算法

  • 現行 16 位銀聯卡現行卡號開頭 6 位是 622126~622925 之間的,7 到 15 位是銀行自定義的,
  • 可能是發卡分行,發卡網點,發卡序號,第 16 位是校驗碼。
  • 16 位卡號校驗位采用 Luhm 校驗方法計算:
  • 1,將未帶校驗位的 15 位卡號從右依次編號 1 到 15,位于奇數位號上的數字乘以 2
  • 2,將奇位乘積的個十位全部相加,再加上所有偶數位上的數字
  • 3,將加法和加上校驗位能被 10 整除。
    */
  • (BOOL)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;
    }

  • (BOOL)isIPAddress{
    NSString *regex = [NSString stringWithFormat:@"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$"];
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    BOOL rc = [pre evaluateWithObject:self];

    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;
    }

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容