检查NSString“000001XX”是否是带有intValue的数字

时间:2012-08-29 03:21:33

标签: nsstring

现在我正在尝试在我的应用上添加前端检查,以检测用户是否仅输入文本字段中的数字。

我用:

- (IBAction)checkID:(UITextField *)sender {
if ([sender.text isEqualToString:@""]) {
    sender.text = @"This information is required";
    sender.backgroundColor =[UIColor redColor];
}else if (![sender.text intValue]) {
    sender.text = [sender.text stringByAppendingString:@" is not valid number"];
    sender.backgroundColor =[UIColor redColor];
}
NSLog(@"send.text is %@, intValue is %d",sender.text,[sender.text intValue]);

}

但我发现文本以数字开头,以字符串结尾,其intValue仍然是数字。 在我的文本中,文本是“00001aa”,但intValue是1。

有没有其他方法来过滤掉这个“00001aa”文字?

提前致谢。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用NSRegularExpressionNSCharacterSet(适用于正数)。

对于正则表达式,请使用^[-+]?[0-9]+$

NSRegularExpression *numEx = [NSRegularExpression
    regularExpressionWithPattern:@"^[-+]?[0-9]+$" options:0 error:nil
];
NSLog(@"%ld", [numEx numberOfMatchesInString:@"-200" options:0 range:NSMakeRange(0, 4)]);
NSLog(@"%ld", [numEx numberOfMatchesInString:@"001A" options:0 range:NSMakeRange(0, 4)]);

对于字符集,请使用[NSCharacterSet decimalDigitCharacterSet]

BOOL isNum = [[NSCharacterSet decimalDigitCharacterSet]
    isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:@"001AA"]
];
相关问题