OC 中關于字符串(NSString)的各種實用工具類,電話、銀行卡號窘疮、車牌袋哼、純漢字、IP闸衫、時間戳涛贯、emoji等等

源碼鏈接:https://github.com/qiushuai/SKTool,如果覺得還用的小伙伴記得Star喲!N党觥5芮獭含懊!

秒數(shù)時間轉換

// 秒數(shù)時間轉換
+ (NSString *)distanceTimeWithBeforeTime:(double)time {
    NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
    double distanceTime = now - time;
    NSString * distanceStr;
    
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {
        //小于一分鐘
        distanceStr = @"剛剛";
    } else if (distanceTime <60*60) {
        //時間小于一個小時
        distanceStr = [NSString stringWithFormat:@"%ld分鐘前",(long)distanceTime/60];
    } else if (distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]) {
        //時間小于一天
        distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
    } else if (distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
        } else {
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        
    } else if (distanceTime <24*60*60*365) {
        [df setDateFormat:@"MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    } else {
        [df setDateFormat:@"yyyy-MM-dd HH:mm"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}

隨機字符串

+ (NSString *)RandomString:(double)number {
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < number; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
            
        } else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

判斷用戶輸入是否含有emoji

+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    return returnValue;
}

過濾emoji

+ (NSString *)removeStringIntheEmoji:(NSString *)string {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                               options:0
                                                                 range:NSMakeRange(0, [string length])
                                                          withTemplate:@""];
    return modifiedString;
}

查看App的當前版本號

+ (NSString *)getAppVersion {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    return appVersion;
}

獲取App的build版本

+ (NSString *)getAppBuildVersion {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appBuildVersion = [infoDic objectForKey:@"CFBundleVersion"];
    return appBuildVersion;
}

獲取App名稱

+ (NSString *)getAppName {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appName = [infoDic objectForKey:@"CFBundleDisplayName"];
    return appName;
}

判斷是否為手機號

+ (BOOL)isValidPhoneWithString:(NSString *)phoneString
{
    
    /**
     * 手機號碼
     * 移動:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 聯(lián)通: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 = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     15         * 中國聯(lián)通:China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^((13[0-2])|(145)|(15[5-6])|(17[0,6])|(16[6])|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 中國電信:China Telecom
     * 133,1349,153,180,189,177,173,181(增加)
     */
    NSString * CT = @"^((133)|(153)|(17[7,3])|(19[8,9])|(18[0,1,9]))\\d{8}$";
    /**
     25         * 大陸地區(qū)固話及小靈通
     26         * 區(qū)號: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:phoneString] == YES)
        || ([regextestcm evaluateWithObject:phoneString] == YES)
        || ([regextestct evaluateWithObject:phoneString] == YES)
        || ([regextestcu evaluateWithObject:phoneString] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

把手機號第4-7位變成星號

+ (NSString *)phoneNumToAsterisk:(NSString*)phoneNum
{
    if (![NSString isValidPhoneWithString:phoneNum]) {
        return phoneNum;
    }
    return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3,4) withString:@"****"];
}

把手機號第4-11位變成星號

+ (NSString*)idCardToAsterisk:(NSString *)idCardNum
{
    if (![NSString isValidPhoneWithString:idCardNum]) {
        return idCardNum;
    }
    return [idCardNum stringByReplacingCharactersInRange:NSMakeRange(3, 8) withString:@"********"];
}

判斷字符串是否包含空格

+ (BOOL)isBlank:(NSString *)str
{
    NSRange _range = [str rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        return YES;
    }
    else {
        return NO;
    }
}

郵箱驗證

- (BOOL)isValidEmail
{
    //    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    //    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    //    return [emailTest evaluateWithObject:self];
    
    NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    return [self isValidateWithRegex:emailRegex];
}

車牌號驗證

- (BOOL)isValidCarNo
{
    //    NSString *carRegex = @"^[A-Za-z]{1}[A-Za-z_0-9]{5}$";
    //    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    //    return [carTest evaluateWithObject:self];
    
    //車牌號:湘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]$";//其中\(zhòng)u4e00-\u9fa5表示unicode編碼中漢字已編碼部分,\u9fa5-\u9fff是保留部分衅胀,將來可能會添加
    return [self isValidateWithRegex:carRegex];
    
}

網(wǎng)址驗證

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

是否郵政編碼

- (BOOL)isValidPostalcode {
    NSString *phoneRegex = @"^[0-8]\\d{5}(?!\\d)$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

是否純漢字

- (BOOL)isValidChinese;
{
    NSString *phoneRegex = @"^[\u4e00-\u9fa5]+$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

是否符合IP格式

- (BOOL)isValidIP;
{
    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;
}

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

/** 銀行卡號有效性問題Luhn算法
 *  現(xiàn)行 16 位銀聯(lián)卡現(xiàn)行卡號開頭 6 位是 622126~622925 之間的岔乔,7 到 15 位是銀行自定義的,
 *  可能是發(fā)卡分行滚躯,發(fā)卡網(wǎng)點雏门,發(fā)卡序號,第 16 位是校驗碼掸掏。
 *  16 位卡號校驗位采用 Luhm 校驗方法計算:
 *  1茁影,將未帶校驗位的 15 位卡號從右依次編號 1 到 15,位于奇數(shù)位號上的數(shù)字乘以 2
 *  2丧凤,將奇位乘積的個十位全部相加募闲,再加上所有偶數(shù)位上的數(shù)字
 *  3,將加法和加上校驗位能被 10 整除愿待。
 */
- (BOOL)isValidBankCard //  銀行卡驗證
{
    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位倒序存進數(shù)組
        [forwardDescArr addObject:forwardArr[i]];
    }
    
    NSMutableArray * arrOddNum = [[NSMutableArray alloc] initWithCapacity:0];//奇數(shù)位*2的積 < 9
    NSMutableArray * arrOddNum2 = [[NSMutableArray alloc] initWithCapacity:0];//奇數(shù)位*2的積 > 9
    NSMutableArray * arrEvenNum = [[NSMutableArray alloc] initWithCapacity:0];//偶數(shù)位數(shù)組
    
    for (int i=0; i< forwardDescArr.count; i++) {
        NSInteger num = [forwardDescArr[i] intValue];
        if (i%2) {//偶數(shù)位
            [arrEvenNum addObject:[NSNumber numberWithInteger:num]];
        }else{//奇數(shù)位
            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)isValidIdCardNum
{
    NSString *value = [self copy];
    value = [value stringByReplacingOccurrencesOfString:@"X" withString:@"x"];
    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 NO;
    }
    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|20[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|20[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)] uppercaseString]]) {
                    return YES;// 檢測ID的校驗位
                }else {
                    return NO;
                }
            }else {
                return NO;
            }
            
        default:
            return NO;
    }
    return NO;
}

判斷字符串中是否含有非法字符

+ (BOOL)isContainErrorCharacter:(NSString *)content {
    NSString *str = @"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}

判斷字符串中包含空格換行

+ (BOOL)isEmpty:(NSString* )string {
    if (!string) {
        return true;
    }
    else {
        NSCharacterSet *chara = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString* str =[string stringByTrimmingCharactersInSet:chara];
        if (str.length ==0) {
            return true;
        }
        else{
            return false;
        }
    }
}

截取字符串中的數(shù)字

+ (NSString *)getPhoneNumberFomat:(NSString *)number {
    NSMutableArray *characters = [NSMutableArray array];
    NSMutableString *mutStr = [NSMutableString string];
    // 分離出字符串中的所有字符浩螺,并存儲到數(shù)組characters中
    for (int i = 0; i < number.length; i ++) {
        NSString *subString = [number substringToIndex:i + 1];
        
        subString = [subString substringFromIndex:i];
        
        [characters addObject:subString];
    }
    // 利用正則表達式,匹配數(shù)組中的每個元素仍侥,判斷是否是數(shù)字要出,將數(shù)字拼接在可變字符串mutStr中
    for (NSString *b in characters) {
        NSString *regex = @"^[0-9]*$";
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];// 謂詞
        BOOL isShu = [pre evaluateWithObject:b];// 對b進行謂詞運算
        if (isShu) {
            [mutStr appendString:b];
        }
    }
    return mutStr;
}

獲取設備聯(lián)網(wǎng)IP地址

+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

獲取UDID唯一標識

+ (NSString *)getUDID
{
    return [[NSUUID UUID] UUIDString];
}

去掉兩端空格和換行符

- (NSString *)stringByTrimmingBlank
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

正則去除HTML標簽

+ (NSString *)getNormalStringFilterHTMLString:(NSString *)htmlStr
{
    NSString *normalStr = htmlStr.copy;
    //判斷字符串是否有效
    if (!normalStr || normalStr.length == 0 || [normalStr isEqual:[NSNull null]]) return @"";
    
    //過濾正常標簽
    NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil];
    normalStr = [regularExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
    
    //過濾占位符
    NSRegularExpression *plExpression=[NSRegularExpression regularExpressionWithPattern:@"&[^;]+;" options:NSRegularExpressionCaseInsensitive error:nil];
    normalStr = [plExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
    
    //過濾空格
    NSRegularExpression *spaceExpression=[NSRegularExpression regularExpressionWithPattern:@"^\\s*|\\s*$" options:NSRegularExpressionCaseInsensitive error:nil];
    normalStr = [spaceExpression stringByReplacingMatchesInString:normalStr options:NSMatchingReportProgress range:NSMakeRange(0, normalStr.length) withTemplate:@""];
    
    return normalStr;
}

過濾HTML標簽

+ (NSString *)removeStringIntheHTML:(NSString *)html
{
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<[^>]*>" options:NSRegularExpressionCaseInsensitive error:&error];
    if (!error) {
        html = [regex stringByReplacingMatchesInString:html options:0 range:NSMakeRange(0, html.length) withTemplate:@"$2$1"];
    } else {
        NSLog(@"%@", error);
    }
    
    NSArray *html_code = @[
                           @"\"", @"'", @"&", @"<", @">",
                           @"", @"?", @"¢", @"£", @"¤",
                           @"¥", @"|", @"§", @"¨", @"?",
                           @"a", @"?", @"?", @"", @"?",
                           @"ˉ", @"°", @"±", @"2", @"3",
                           
                           @"′", @"μ", @"?", @"·", @"?",
                           @"1", @"o", @"?", @"?", @"?",
                           @"?", @"?", @"×", @"÷", @"à",
                           @"á", @"?", @"?", @"?", @"?",
                           @"?", @"?", @"è", @"é", @"ê",
                           
                           @"?", @"ì", @"í", @"?", @"?",
                           @"D", @"?", @"ò", @"ó", @"?",
                           @"?", @"?", @"?", @"ù", @"ú",
                           @"?", @"ü", @"Y", @"T", @"?",
                           @"à", @"á", @"a", @"?", @"?",
                           
                           @"?", @"?", @"?", @"è", @"é",
                           @"ê", @"?", @"ì", @"í", @"?",
                           @"?", @"e", @"?", @"ò", @"ó",
                           @"?", @"?", @"?", @"?", @"ù",
                           @"ú", @"?", @"ü", @"y", @"t",
                           
                           @"?", @"?", @"?", @"?", @"?",
                           @"?", @"∈", @"?", @"?", @"∏",
                           @"∑", @"?", @"?", @"√", @"∝",
                           @"∞", @"∠", @"∧", @"∨", @"∩",
                           @"∪", @"∫", @"∴", @"~", @"?",
                           
                           @"≈", @"≠", @"≡", @"≤", @"≥",
                           @"?", @"?", @"?", @"?", @"?",
                           @"⊕", @"?", @"⊥", @"?", @"Α",
                           @"Β", @"Γ", @"Δ", @"Ε", @"Ζ",
                           @"Η", @"Θ", @"Ι", @"Κ", @"Λ",
                           
                           @"Μ", @"Ν", @"Ξ", @"Ο", @"Π",
                           @"Ρ", @"Σ", @"Τ", @"Υ", @"Φ",
                           @"Χ", @"Ψ", @"Ω", @"α", @"β",
                           @"γ", @"δ", @"ε", @"ζ", @"η",
                           @"θ", @"ι", @"κ", @"λ", @"μ",
                           
                           @"ν", @"ξ", @"ο", @"π", @"ρ",
                           @"?", @"σ", @"τ", @"υ", @"φ",
                           @"χ", @"ψ", @"ω", @"?", @"?",
                           @"?", @"?", @"?", @"?", @"?",
                           @"?", @"?", @"?", @"?", @"",
                           
                           @"", @"", @"", @"", @"",
                           @"", @"–", @"—", @"‘", @"’",
                           @"?", @"“", @"”", @"?", @"?",
                           @"?", @"?", @"…", @"‰", @"′",
                           @"″", @"?", @"?", @" ̄", @"€",
                           
                           @"?", @"←", @"↑", @"→", @"↓",
                           @"?", @"?", @"?", @"?", @"?",
                           @"?", @"?", @"?", @"?", @"?",
                           @"?",
                           ];
    NSArray *code = @[
                      @"&quot;", @"&apos;", @"&amp;", @"&lt;", @"&gt;",
                      @"&nbsp;", @"&iexcl;", @"&cent;", @"&pound;", @"&curren;",
                      @"&yen;", @"&brvbar;", @"&sect;", @"&uml;", @"&copy;",
                      @"&ordf;", @"&laquo;", @"&not;", @"&shy;", @"&reg;",
                      @"&macr;", @"&deg;", @"&plusmn;", @"&sup2;", @"&sup3;",
                      
                      @"&acute;", @"&micro;", @"&para;", @"&middot;", @"&cedil;",
                      @"&sup1;", @"&ordm;", @"&raquo;", @"&frac14;", @"&frac12;",
                      @"&frac34;", @"&iquest;", @"&times;", @"&divide;", @"&Agrave;",
                      @"&Aacute;", @"&Acirc;", @"&Atilde;", @"&Auml;", @"&Aring;",
                      @"&AElig;", @"&Ccedil;", @"&Egrave;", @"&Eacute;", @"&Ecirc;",
                      
                      @"&Euml;", @"&Igrave;", @"&Iacute;", @"&Icirc;", @"&Iuml;",
                      @"&ETH;", @"&Ntilde;", @"&Ograve;", @"&Oacute;", @"&Ocirc;",
                      @"&Otilde;", @"&Ouml;", @"&Oslash;", @"&Ugrave;", @"&Uacute;",
                      @"&Ucirc;", @"&Uuml;", @"&Yacute;", @"&THORN;", @"&szlig;",
                      @"&agrave;", @"&aacute;", @"&acirc;", @"&atilde;", @"&auml;",
                      
                      @"&aring;", @"&aelig;", @"&ccedil;", @"&egrave;", @"&eacute;",
                      @"&ecirc;", @"&euml;", @"&igrave;", @"&iacute;", @"&icirc;",
                      @"&iuml;", @"&eth;", @"&ntilde;", @"&ograve;", @"&oacute;",
                      @"&ocirc;", @"&otilde;", @"&ouml;", @"&oslash;", @"&ugrave;",
                      @"&uacute;", @"&ucirc;", @"&uuml;", @"&yacute;", @"&thorn;",
                      
                      @"&yuml;", @"&forall;", @"&part;", @"&exists;", @"&empty;",
                      @"&nabla;", @"&isin;", @"&notin;", @"&ni;", @"&prod;",
                      @"&sum;", @"&minus;", @"&lowast;", @"&radic;", @"&prop;",
                      @"&infin;", @"&ang;", @"&and;", @"&or;", @"&cap;",
                      @"&cup;", @"&int;", @"&there4;", @"&sim;", @"&cong;",
                      
                      @"&asymp;", @"&ne;", @"&equiv;", @"&le;", @"&ge;",
                      @"&sub;", @"&sup;", @"&nsub;", @"&sube;", @"&supe;",
                      @"&oplus;", @"&otimes;", @"&perp;", @"&sdot;", @"&Alpha;",
                      @"&Beta;", @"&Gamma;", @"&Delta;", @"&Epsilon;", @"&Zeta;",
                      @"&Eta;", @"&Theta;", @"&Iota;", @"&Kappa;", @"&Lambda;",
                      
                      @"&Mu;", @"&Nu;", @"&Xi;", @"&Omicron;", @"&Pi;",
                      @"&Rho;", @"&Sigma;", @"&Tau;", @"&Upsilon;", @"&Phi;",
                      @"&Chi;", @"&Psi;", @"&Omega;", @"&alpha;", @"&beta;",
                      @"&gamma;", @"&delta;", @"&epsilon;", @"&zeta;", @"&eta;",
                      @"&theta;", @"&iota;", @"&kappa;", @"&lambda;", @"&mu;",
                      
                      @"&nu;", @"&xi;", @"&omicron;", @"&pi;", @"&rho;",
                      @"&sigmaf;", @"&sigma;", @"&tau;", @"&upsilon;", @"&phi;",
                      @"&chi;", @"&psi;", @"&omega;", @"&thetasym;", @"&upsih;",
                      @"&piv;", @"&OElig;", @"&oelig;", @"&Scaron;", @"&scaron;",
                      @"&Yuml;", @"&fnof;", @"&circ;", @"&tilde;", @"&ensp;",
                      
                      @"&emsp;", @"&thinsp;", @"&zwnj;", @"&zwj;", @"&lrm;",
                      @"&rlm;", @"&ndash;", @"&mdash;", @"&lsquo;", @"&rsquo;",
                      @"&sbquo;", @"&ldquo;", @"&rdquo;", @"&bdquo;", @"&dagger;",
                      @"&Dagger;", @"&bull;", @"&hellip;", @"&permil;", @"&prime;",
                      @"&Prime;", @"&lsaquo;", @"&rsaquo;", @"&oline;", @"&euro;",
                      
                      @"&trade;", @"&larr;", @"&uarr;", @"&rarr;", @"&darr;",
                      @"&harr;", @"&crarr;", @"&lceil;", @"&rceil;", @"&lfloor;",
                      @"&rfloor;", @"&loz;", @"&spades;", @"&clubs;", @"&hearts;",
                      @"&diams;",
                      ];
    /*
     NSArray *code_hex = @[
     @"&#34;", @"&#39;", @"&#38;", @"&#60;", @"&#62;",
     @"&#160;", @"&#161;", @"&#162;", @"&#163;", @"&#164;",
     @"&#165;", @"&#166;", @"&#167;", @"&#168;", @"&#169;",
     @"&#170;", @"&#171;", @"&#172;", @"&#173;", @"&#174;",
     @"&#175;", @"&#176;", @"&#177;", @"&#178;", @"&#179;",
     
     @"&#180;", @"&#181;", @"&#182;", @"&#183;", @"&#184;",
     @"&#185;", @"&#186;", @"&#187;", @"&#188;", @"&#189;",
     @"&#190;", @"&#191;", @"&#215;", @"&#247;", @"&#192;",
     @"&#193;", @"&#194;", @"&#195;", @"&#196;", @"&#197;",
     @"&#198;", @"&#199;", @"&#200;", @"&#201;", @"&#202;",
     
     @"&#203;", @"&#204;", @"&#205;", @"&#206;", @"&#207;",
     @"&#208;", @"&#209;", @"&#210;", @"&#211;", @"&#212;",
     @"&#213;", @"&#214;", @"&#216;", @"&#217;", @"&#218;",
     @"&#219;", @"&#220;", @"&#221;", @"&#222;", @"&#223;",
     @"&#224;", @"&#225;", @"&#226;", @"&#227;", @"&#228;",
     
     @"&#229;", @"&#230;", @"&#231;", @"&#232;", @"&#233;",
     @"&#234;", @"&#235;", @"&#236;", @"&#237;", @"&#238;",
     @"&#239;", @"&#240;", @"&#241;", @"&#242;", @"&#243;",
     @"&#244;", @"&#245;", @"&#246;", @"&#248;", @"&#249;",
     @"&#250;", @"&#251;", @"&#252;", @"&#253;", @"&#254;",
     
     @"&#255;", @"&#8704;", @"&#8706;", @"&#8707;", @"&#8709;",
     @"&#8711;", @"&#8712;", @"&#8713;", @"&#8715;", @"&#8719;",
     @"&#8721;", @"&#8722;", @"&#8727;", @"&#8730;", @"&#8733;",
     @"&#8734;", @"&#8736;", @"&#8743;", @"&#8744;", @"&#8745;",
     @"&#8746;", @"&#8747;", @"&#8756;", @"&#8764;", @"&#8773;",
     
     @"&#8776;", @"&#8800;", @"&#8801;", @"&#8804;", @"&#8805;",
     @"&#8834;", @"&#8835;", @"&#8836;", @"&#8838;", @"&#8839;",
     @"&#8853;", @"&#8855;", @"&#8869;", @"&#8901;", @"&#913;",
     @"&#914;", @"&#915;", @"&#916;", @"&#917;", @"&#918;",
     @"&#919;", @"&#920;", @"&#921;", @"&#922;", @"&#923;",
     
     @"&#924;", @"&#925;", @"&#926;", @"&#927;", @"&#928;",
     @"&#929;", @"&#931;", @"&#932;", @"&#933;", @"&#934;",
     @"&#935;", @"&#936;", @"&#937;", @"&#945;", @"&#946;",
     @"&#947;", @"&#948;", @"&#949;", @"&#950;", @"&#951;",
     @"&#952;", @"&#953;", @"&#954;", @"&#923;", @"&#956;",
     
     @"&#925;", @"&#958;", @"&#959;", @"&#960;", @"&#961;",
     @"&#962;", @"&#963;", @"&#964;", @"&#965;", @"&#966;",
     @"&#967;", @"&#968;", @"&#969;", @"&#977;", @"&#978;",
     @"&#982;", @"&#338;", @"&#339;", @"&#352;", @"&#353;",
     @"&#376;", @"&#402;", @"&#710;", @"&#732;", @"&#8194;",
     
     @"&#8195;", @"&#8201;", @"&#8204;", @"&#8205;", @"&#8206;",
     @"&#8207;", @"&#8211;", @"&#8212;", @"&#8216;", @"&#8217;",
     @"&#8218;", @"&#8220;", @"&#8221;", @"&#8222;", @"&#8224;",
     @"&#8225;", @"&#8226;", @"&#8230;", @"&#8240;", @"&#8242;",
     @"&#8243;", @"&#8249;", @"&#8250;", @"&#8254;", @"&#8364;",
     
     @"&#8482;", @"&#8592;", @"&#8593;", @"&#8594;", @"&#8595;",
     @"&#8596;", @"&#8629;", @"&#8968;", @"&#8969;", @"&#8970;",
     @"&#8971;", @"&#9674;", @"&#9824;", @"&#9827;", @"&#9829;",
     @"&#9830;",
     ];
     */
    NSInteger idx = 0;
    for (NSString *obj in code) {
        html = [html stringByReplacingOccurrencesOfString:(NSString *)obj withString:html_code[idx]];
        idx++;
    }
    return html;
}

工商稅號

- (BOOL)isValidTaxNo
{
    NSString *emailRegex = @"[0-9]\\d{13}([0-9]|X)$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

刪除字符串中的數(shù)字

+ (NSString *)stringDeleteNumber:(NSString *)str
{
    NSMutableString *str1 = [NSMutableString stringWithString:str];
    for (int i = 0; i < str1.length; i++) {
        unichar c = [str1 characterAtIndex:i];
        NSRange range = NSMakeRange(i, 1);
        if ( c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') { //此處可以是任何字符
            [str1 deleteCharactersInRange:range];
            --i;
        }
    }
    NSString *newstr = [NSString stringWithString:str1];
    return newstr;
}

數(shù)字如果前面有0,保留去掉0之后的數(shù)據(jù)

+ (NSString*)getTheCorrectNum:(NSString*)tempString
{
    while ([tempString hasPrefix:@"0"])
    {
        tempString = [tempString substringFromIndex:1];
    }
    return tempString;
}

拼接字符串

- (NSString *)addString:(NSString *)str
{
    return [NSString stringWithFormat:@"%@%@",self,str];
}

獲取當前時間戳

+ (NSString *)currentTimeStr
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//獲取當前時間0秒后的時間
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精確到毫秒农渊,不乘就是精確到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

刪除字符串最后一位字符

+ (NSString *)removeLastOneChar:(NSString *)origin {
    NSString *cutted;
    if([origin length] > 0){
        cutted = [origin substringToIndex:([origin length]-1)];
    }else{
        cutted = origin;
    }
    return cutted;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末患蹂,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子砸紊,更是在濱河造成了極大的恐慌传于,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件醉顽,死亡現(xiàn)場離奇詭異沼溜,居然都是意外死亡,警方通過查閱死者的電腦和手機徽鼎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門盛末,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人否淤,你說我怎么就攤上這事悄但。” “怎么了石抡?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵檐嚣,是天一觀的道長。 經(jīng)常有香客問我,道長嚎京,這世上最難降的妖魔是什么嗡贺? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮鞍帝,結果婚禮上诫睬,老公的妹妹穿的比我還像新娘。我一直安慰自己帕涌,他們只是感情好摄凡,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蚓曼,像睡著了一般亲澡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上纫版,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天床绪,我揣著相機與錄音,去河邊找鬼其弊。 笑死癞己,一個胖子當著我的面吹牛,可吹牛的內容都是我干的瑞凑。 我是一名探鬼主播末秃,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼籽御!你這毒婦竟也來了?” 一聲冷哼從身側響起惰匙,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤技掏,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后项鬼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哑梳,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年绘盟,在試婚紗的時候發(fā)現(xiàn)自己被綠了鸠真。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡龄毡,死狀恐怖吠卷,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情沦零,我是刑警寧澤祭隔,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站路操,受9級特大地震影響疾渴,放射性物質發(fā)生泄漏千贯。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一搞坝、第九天 我趴在偏房一處隱蔽的房頂上張望搔谴。 院中可真熱鬧,春花似錦桩撮、人聲如沸敦第。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽申尼。三九已至,卻和暖如春垫桂,著一層夾襖步出監(jiān)牢的瞬間师幕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工诬滩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留霹粥,地道東北人。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓疼鸟,卻偏偏與公主長得像后控,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子空镜,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353