正则表达式以匹配mm/dd/yyyy hh:mm:ss AM或PM [英] Regex to match mm/dd/yyyy hh:mm:ss AM or PM
问题描述
我有一个为时间戳创建信息的程序,该时间戳必须匹配以下格式: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
例如:
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.
我知道如何匹配数字/\d+/
和非空格字符,但是匹配数字不会抓住:
,/
,AM or PM
.抓住非空白区域将获得除明显的空白区域以外的所有内容.
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.
因此,回顾一下,我需要一种方法来验证格式化的时间和日期:MM/DD/YYYY HH:MM:SS AM or PM
可以包含20到22个字符(包括空格)或是否作为用户输入给出.
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.
我需要的示例:
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'
推荐答案
此正则表达式可为您验证输入内容:
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
这将验证以下任一输入行:
This will validate either of these inputs lines:
10/22/2016 9:15:32 PM
9/9/2016 9:9:5 AM
这篇关于正则表达式以匹配mm/dd/yyyy hh:mm:ss AM或PM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!