如何在 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;
}
试试这个作为你的正则表达式 ^[0-9]+$
试试这个,对你有帮助
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
if (textField == tfMobile)
{
NSString *strRegExp=@"[0-9]*";
NSPredicate *MobNumTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",strRegExp];
if([MobNumTest evaluateWithObject:textField.text]==NO)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct contact no." delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
[alert release];
tfMobile.text =@"";
}
}
}
在需要的地方调用此方法。如果 checkString 仅包含数字,则返回 true
- (BOOL) textFieldValidation:(NSString *)checkString {
NSString *stricterFilterString = @"[0-9]+";//here + is for one or more numerals(use * for zero or more numerals)
NSString *regEx = stricterFilterString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
return [emailTest evaluateWithObject:checkString];
}