iOS中运用正则表达式
iOS中运用正则表达式来匹配短信验证码,电话号码,邮箱等是比较常见的。
在iOS中运用正则表达式主要有三种方式:
-:通过谓词下面是实例代码:
- (BOOL)regularExpresionWith:(NSString*)str{ NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES '^1[358][0-9]{9}$'"]; BOOL isvalid = [pre evaluateWithObject:str]; return isvalid; }
二:通过string方法:
- (BOOL)regularExpresionWith:(NSString*)str{ NSString*regex = @"^1[358][0-9]{9}$"; NSRange range = [str rangeOfString:regex options:NSRegularExpressionSearch]; if (range.length == 0) { return NO; } return YES;; }
三:通过NSRegularExpression
NSError *error = nil; NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern: @"^([0-9]{6})$" options:0 error:&error]; if (!error) { //result != null 代表能匹配 NSTextCheckingResult *result = [regular firstMatchInString:str options:0 range:NSMakeRange(0, [str length])]; NSLog(@"result ====%@",result); }else{ NSLog(@"发生错误无法进行匹配!"); }