iOS 常用的正则表达式

2016-09-03  本文已影响424人  emily_sky
一、项目实例:

RegularTool.h
#import <Foundation/Foundation.h>

@interface RegularTool : NSObject
/**
 *正则匹配中文
 */
+(BOOL)isChinese:(NSString *)string;
/**
 * 验证手机号码
 */
+(BOOL)isphone:(NSString *)string;
/**
 * 验证邮箱
 */
+(BOOL)isEmail:(NSString *)string;

/**
 * 6到16位不含特殊字符的数字与英文字母组合的密码
 */
+(BOOL)isPwd:(NSString *)string;
@end

RegularTool.m

#import "RegularTool.h"

@implementation RegularTool

#pragma mark----正则匹配中文------
+(BOOL)isChinese:(NSString *)string{
    //[\u4e00-\u9fa5]  一个中文
    NSString *chinese = @"^[u4e00-u9fa5]{0,}$";
    //NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取
    NSPredicate *chinesejudge = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",chinese];
    return [chinesejudge evaluateWithObject:string];
}
#pragma mark ------手机号码验证-------
+(BOOL)isphone:(NSString *)string{
    //^1[34578]\\d{9}$
    NSString *str_text = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
    NSPredicate *textcheck =[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str_text];

    return [textcheck evaluateWithObject:string];
}
#pragma mark ------邮箱验证-------
+(BOOL)isEmail:(NSString *)string{
    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:string];
}

#pragma mark ---6到16位不含特殊字符的数字与英文字母组合的密码
+(BOOL)isPwd:(NSString *)string{

    NSString *str_text = @"^[0-9A-Za-z]{6,16}$";
    NSPredicate *textcheck =[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str_text];

    BOOL result =false;
    result = [textcheck evaluateWithObject:string];
    if(!result){
        NSLog(@"密码必须数字跟字母组合");
        return NO;
    }
    str_text =@"^(?![^0-9]+$)(?![^a-zA-Z]+$).+$";
    textcheck =[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str_text];
    result = [textcheck evaluateWithObject:string];

  if(!result){
        NSLog(@"密码必须数字跟字母组合");
        return NO;
    }
    return [textcheck evaluateWithObject:string];
}

@end
二、常用的正则表达式:
上一篇下一篇

猜你喜欢

热点阅读