如何在iOS sdk中使用正则表达式

如何在iOS sdk中使用正则表达式?

我需要使用正则表达式validationUITextField只允许将数值放入UITextField

试试这个正则表达式^ [0-9] + $

在你的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; } 

试试这个,对你有所帮助

 - (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]; 

}