需要一个正则表达式来匹配日期和可选时间 [英] Need a regex pattern to match date with optional time

查看:193
本文介绍了需要一个正则表达式来匹配日期和可选时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个与可选时间匹配日期的正则表达式模式。

日期应为美元有效日期 m / d / yyyy 格式。时间应该是 h:mm:ss am / pm 或24小时时间 hh:mm:ss / p>

The date should be a valid U.S. date in m/d/yyyy format. The time should be h:mm:ss am/pm or 24-hour time hh:mm:ss.


比赛:9/1/2011 | 9/1/2011 10:00 am | 9/1/2011 10:00 AM | 9/1/2011 10:00:00

Matches: 9/1/2011 | 9/1/2011 10:00 am | 9/1/2011 10:00 AM | 9/1/2011 10:00:00

此模式将用于Ruby on Rails项目,因此应该在通过Ruby可以使用的格式。请参阅 http://rubular.com/ 进行测试。

This pattern will be used in a Ruby on Rails project, so it should be in a format usable via Ruby. See http://rubular.com/ for testing.

这是我现有的日期模式(可能是过度杀死):

Here's my existing date pattern (which may be an over-kill):

DATE_PATTERN = /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}/


推荐答案

嗯,这是我结束了什么使用更严格的军事时间:

Well, here's what I ended up with; using stricter military time:

DATE_TIME_FORMAT = /^([0,1]?\d{1})\/([0-2]?\d{1}|[3][0,1]{1})\/([1]{1}[9]{1}[9]{1}\d{1}|[2-9]{1}\d{3})\s([0]?\d|1\d|2[0-3]):([0-5]\d):([0-5]\d)$/




匹配:1/19/2011 23:59:59

Matches: 1/19/2011 23:59:59

捕获:


  1. 1

  2. 19

  3. 2011

  4. 23

  5. 59

  6. 59

  1. 1
  2. 19
  3. 2011
  4. 23
  5. 59
  6. 59


这篇关于需要一个正则表达式来匹配日期和可选时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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