iOS零碎知识iOS DeveloperiOS学习笔记

iOS 一些常用的正则

2016-06-27  本文已影响263人  chy1ee

待补充,项目中暂时就用了这么多

 //  NSString+regex.h
//  CircleFace
//
//  Created by chylee on 16/4/12.
//  Copyright © 2016年 . All rights reserved.
//
#import <Foundation/Foundation.h>

@interface NSString (regex)

/**
 *  判断字符串格式是否为手机号
 */
-(BOOL)isPhoneNumber;

/**
 *  判断字符串格式是否为六位数字验证码
 */
-(BOOL)isVerify;

/**
 *  判断字符串格式是否为字母或数字组成的5-15位密码
 */
-(BOOL)isPassword;
/**
 *  判断身份证是否合法
 */
-(BOOL)isID: (NSString *)identityCard;

/**
 *  判断圈脸号是否合法
 */
-(BOOL)isCirecleNo;

/**
 * 判断昵称
 */

-(BOOL)isNiceName;

@end






#import "NSString+regex.h"

@implementation NSString (regex)

/**
 *  判断字符串格式是否为手机号
 */
-(BOOL)isPhoneNumber{
    return [self getIsMatches:@"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$"];
}

/**
 *  判断字符串格式是否为4位数字验证码
 */
-(BOOL)isVerify{
    return [self getIsMatches:@"^\\d{4}$"];
}

/**
 *  判断字符串格式是否为字母或数字组成的6-15位密码
 */
-(BOOL)isPassword{
    return [self getIsMatches:@"^[A-Za-z0-9_]{6,15}$"];
}

/**
 *  判断圈脸号是否合法
 */
-(BOOL)isCirecleNo{
    return [self getIsMatches:@"[a-zA-Z0-9_]+"];
}
/**
 *  判断昵称
 */
-(BOOL)isNiceName{
    return [self getIsMatches:@"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+"];
}

- (BOOL)isID:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
}
    flag = [self getIsMatches:identityCard];
    flag = flag && [self isRealIDCode:identityCard];
    return flag;

}

- (BOOL)isRealIDCode:(NSString *)realCode {
    if (realCode.length < 18) {
        return false;
    }
    NSArray *ds = @[@7, @9, @10, @5, @8, @4, @2, @1, @6, @3, @7, @9, @10, @5, @8, @4, @2];
NSInteger total = 0;

    for (NSInteger i = 0; i < 17; i++) {
    
    NSRange currentRange = NSMakeRange(i, 1);
    NSString *currentCode = [realCode substringWithRange:currentRange];
    NSInteger currentCodeInteger = [currentCode integerValue];
    
    NSInteger dsi = [ds[i] integerValue];
    total += currentCodeInteger * dsi;
}

    total = total % 11;
    NSArray *ends = @[@"1", @"0", @"x", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    NSString *end = ends[total];

    if ([end isEqualToString:[[realCode substringWithRange:NSMakeRange(17, 1)] lowercaseString]]) {
        return YES;
    }
        return NO;
  }
/**
 *  判断方法
 *
 *  @param Regex 判断标准
 */
-(BOOL)getIsMatches:(NSString *)Regex{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",Regex];
return [predicate evaluateWithObject:self];
}
@end
上一篇下一篇

猜你喜欢

热点阅读