//用于 testField: shouldChangeCharactersInRange: replacementString:里输入过滤
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 输入校验,只允许数字
NSString *regex = @"^[0-9]*$";
//NSString *regex = @"^[0-9.]*$";//数字和小数点
NSString *fieldStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
BOOL isInput = [self textFieldOfRegex:regex andText:fieldStr];
if (!isInput) {
return NO;
}
}
//正则表达式
- (BOOL)textFieldOfRegex:(NSString*)regex andText:(NSString*)text {
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [pred evaluateWithObject:text];
}
iOS 正则表达式过滤
最新推荐文章于 2023-08-24 14:05:23 发布