正则表达式匹配 mm/dd/yyyy hh:mm:ss AM 或 PM [英] Regex to match mm/dd/yyyy hh:mm:ss AM or PM

查看:37
本文介绍了正则表达式匹配 mm/dd/yyyy hh:mm:ss AM 或 PM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建时间戳信息的程序,时间戳必须符合以下格式:MM/DD/YYYY HH:MM:SS AM 或 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

2014 年 9 月 14 日晚上 9:16:32

我需要一种使用正则表达式匹配此信息的方法,但它不必是正则表达式.对此的任何帮助将不胜感激.

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+/ 和非空白字符,但是匹配数字不会获取 :/上午或下午.并且抓取非空白将抓取除明显空白之外的所有内容.

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 或 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]Mz

正则表达式演示

这将验证以下任一输入行:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆