使用正则表达式验证时间

时间:2012-06-25 13:17:57

标签: regex validation time

我是Objective-C代码编程的新手......这是我第一次在Stackoverflow上发布一个问题。

有人可以说我为什么这段代码不起作用? 我在测试网站上测试了正则表达式并且工作正常,但在Xcode中不起作用....我需要以这种格式验证时间(HH:MM)。

谢谢大家......

(代码)

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *expression = [[NSString alloc] init];
    if (textField == self.TB_orarioPartenza)
    {

       expression = @"^([0-1][0-9]|[2][0-3]):([0-5][0-9])$";
    }
    if (textField == self.TB_numGiri) {
        expression = @"^d{2}";
    }

    NSString *newString =[textField.text stringByReplacingCharactersInRange:range withString:string];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression 
                                                                           options:0 
                                                                             error:nil];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                        options:0
                                                          range:NSMakeRange(0, [newString length])];         
    if (numberOfMatches == 0) return NO;        

    return YES;

}

1 个答案:

答案 0 :(得分:1)

对于 h:mm 格式(例如“9:35”),请使用正则表达式:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

对于 hh:mm 格式(例如“09:35”),请使用正则表达式:

^(?:0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$