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 に答える