QuickBrownFox wrote:
Hey everybody,

I'm using a regular expression for validation here at work that I wanted some advice on. Specifically, it checks to see if the time is formatted correctly in the 12-hour format (hh:mm:ss (AM|PM)). So far, this is what I've got:

/^(0?[1-9]|1[0-2]):([0-5][0-9]):9[0-5][0-9]) (AM|PM)$/
^
Looks fine, except I think you missed a shift key (above the marker, if that 9 is a (, then everything's fine). Although I'd relax the requirement for seconds and allow variable whitespace:


/^(0?[1-9]|1[0-2]):([0-5][0-9])(:([0-5][0-9]))?\s*(AM|PM)$/

Now, my question is this: How would I change this to only allow times from 8:00 AM to 5:00 PM.

Rather than trying a regex, I'd use logic in the language after the regex. For example, if I were in perl:


sub check_time
{
   # get input and check general format

   my $time = shift;
   if ($time =~
       /^(0?[1-9]|1[0-2]):([0-5][0-9])(:([0-5][0-9]))?\s*(AM|PM)$/)
   {
      # get parts and convert to 24 hours string w/o colons (default
      # seconds to 0

      my ($hour, $min, $sec, $am_or_pm) = ($1, $2, $4, $5);
      $hour += 12 if $am_or_pm eq 'PM';
      $sec = 0 unless $sec;
      my $new_time = $hour . $min . $sec;

# make sure the time is between 8AM and 5PM (inclusive)

      return ($new_time ge '080000' and $new_time le '170000');
   }
   else { return 0; }
}

Jacob Fugal


____________________
BYU Unix Users Group http://uug.byu.edu/ ___________________________________________________________________
List Info: http://uug.byu.edu/cgi-bin/mailman/listinfo/uug-list

Reply via email to