2

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

我需要UITextField使用正则表达式进行验证,只允许将数值放入UITextField.

4

4 回答 4

3

在你的 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;
}
于 2012-06-26T11:20:39.157 回答
2

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

于 2012-06-26T11:18:15.223 回答
1

试试这个,对你有帮助

- (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 =@"";

        }

    }
    }
于 2012-06-26T11:26:56.610 回答
0

在需要的地方调用此方法。如果 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];

}

于 2012-06-26T11:27:12.927 回答