1

UITextBoxfield中,我插入了一些值,并且我想使用正则表达式匹配字符串..现在我希望文本框文本应该只匹配最多 3 位的数字,当我按下按钮时它应该可以工作......我正在尝试的是这不起作用::-

-(IBAction)ButtonPress{

NSString *string =activity.text;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];

 if ([activity.text isEqualToString:modifiedString ])
{ // work only if this matches numeric value from the text box text
}}
4

3 回答 3

2

您的代码将所有匹配项替换为一个空字符串,因此如果有匹配项,它将被一个空字符串替换,并且您的检查将永远不会起作用。相反,只需向正则表达式询问第一个匹配的范围:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:NULL];
NSRange range = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];

if(range.location != NSNotFound)
{
    // The regex matches the whole string, so if a match is found, the string is valid
    // Also, your code here 
}

您也可以只询问匹配的数量,如果它不为零,则字符串包含介于0和之间的数字,999因为您的正则表达式匹配整个字符串。

于 2013-01-09T05:33:46.583 回答
2
- (BOOL)NumberValidation:(NSString *)string  {
    NSUInteger newLength = [string length];
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return (([string isEqualToString:filtered])&&(newLength <= 3));
}

在您的按钮操作事件中,只需像下面这样使用...

-(IBAction)ButtonPress{

 if ([self NumberValidation:activity.text]) {
        NSLog(@"Macth here");
    }
    else {
        NSLog(@"Not Match here");
    }
}
于 2013-01-09T05:33:58.253 回答
1

请尝试以下代码。

- (BOOL) validate: (NSString *) candidate {
     NSString *digitRegex = @"^[0-9]{1,3}$";
    NSPredicate *regTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", digitRegex];
    return [regTest evaluateWithObject:candidate];
}

-(IBAction)btnTapped:(id)sender{

    if([self validate:[txtEmail text]] ==1)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Correct id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];

    }
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Incoorect id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
}
于 2013-01-09T05:28:58.413 回答