在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
}}
答案 0 :(得分: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
之间的数字,因为您的正则表达式匹配整个字符串。
答案 1 :(得分: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");
}
}
答案 2 :(得分: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];
}
}