如何在iOS sdk中使用正则表达式?
我需要使用正则表达式验证 UITextField
只允许将数值输入 UITextField
。
最佳答案
在你的 shouldChangeCharactersInRange 中你可以这样做
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^([0-9]+$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;
return YES;
}
关于ios - 如何在iOS sdk中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206144/