JohnDoeYo JohnDoeYo - 5 months ago 18
Ruby Question

Regex to match mm/dd/yyyy hh:mm:ss AM or PM

I have a program that creates information for a time stamp, the time stamp has to match the following format:

MM/DD/YYYY HH:MM:SS AM or PM


For example:

06/02/2016 10:14:56 AM


09/14/2014 9:16:32 PM


I need a way to match this information using preferable a regex, however it doesn't have to be a regex. Any help with this would be greatly appreciated.

I know how to match the digits
/\d+/
, and non white space characters, however matching the digits won't grab the
:
,
/
,
AM or PM
. And grabbing the non white space will grab everything except for the obviously white space.

So to recap I need a way to verify that a formatted time and date:
MM/DD/YYYY HH:MM:SS AM or PM
That can contain 20 to 22 characters (including white space) exists or not given as user input.

Example of what I need:

def timestamp
print 'Enter the time stamp to verify: '
ts = gets.chomp
if !(ts[REGEX-HERE])
puts 'Invalid formatting of time stamp'
exit 1
else
puts ts
end
end

# <= 6/1/2016 1:10:5 PM will output '6/1/2016 1:10:5 PM'
# <= 06/01/2016 01:10:05 PM will output 'Invalid formatting of time stamp'
# <= 10/1/2016 1:25:43 AM will output '10/1/2016 1:25:43 AM'
# <= 10/01/2016 01:25:43 AM will output 'Invalid formatting of time stamp'

Answer

This regex should work for you for validation of your inputs:

^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{1,2}:\d{1,2} [AP]M\z

RegEx Demo

This will validate either of these inputs lines:

10/22/2016 9:15:32 PM
9/9/2016 9:9:5 AM