iOS 正则表达式判断UITextField是否为全汉字,全字母,全数字,数字和字母

1. 限制输入框内只能是数字和字母

[textField addTarget:self action:@selector(textFieldDidchange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidchange:(UITextField *)textField {
    NSString *textString = textField.text;
    if (![self inputShouldLetterOrNum:textString] && textString.length > 0) {
        [YFAlertTool alertMessage:@"只能是数字或者字母!"];
        textField.text = self.currentText;
        return;
    }
    self.currentText = textString;
}

2. 判断全汉字

- (BOOL)inputShouldChinese:(NSString *)inputString {
    if (inputString.length == 0) return NO;
    NSString *regex = @"[\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}

3. 判断全数字:

- (BOOL)inputShouldNumber:(NSString *)inputString {
    if (inputString.length == 0) return NO;
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}

4. 判断全字母:

- (BOOL)inputShouldLetter:(NSString *)inputString {
    if (inputString.length == 0) return NO;
    NSString *regex =@"[a-zA-Z]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}

5. 判断仅输入字母或数字:

- (BOOL)inputShouldLetterOrNum:(NSString *)inputString {
    if (inputString.length == 0) return NO;
    NSString *regex =@"[a-zA-Z0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:inputString];
}

你可能感兴趣的:(iOS 正则表达式判断UITextField是否为全汉字,全字母,全数字,数字和字母)