使用多个选项检查长度的正则表达式

时间:2013-08-26 12:19:12

标签: regex date

我需要验证日期格式,可以是11/11/1111/22/2013,即年份块可以是YYYYYY,完整格式将是MM/DD/YYMM/DD/YYYY

我有这段代码

^(\d{1,2})\/(\d{1,2})\/(\d{4})$

我试过

^(\d{1,2})\/(\d{1,2})\/(\d{2}{4})$ // doesn't works, does nothing

^(\d{1,2})\/(\d{1,2})\/(\d{2|4})$ // and it returns null every time

PS:我正在使用Javascript / jQuery

2 个答案:

答案 0 :(得分:8)

^(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})$

\d{2}{4}\d{2|4}都不是正确的正则表达式。你必须分别做两位数数字,然后使用进行组合:(\d{2}|\d{4})

答案 1 :(得分:2)

您可以使用:

^\d\d?/\d\d?/\d\d(?:\d\d)?$

<强>解释

The regular expression:

(?-imsx:^\d\d?/\d\d?/\d\d(?:\d\d)?$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  \d                       digits (0-9)
----------------------------------------------------------------------
  \d?                      digits (0-9) (optional (matching the most
                           amount possible))
----------------------------------------------------------------------
  /                        '/'
----------------------------------------------------------------------
  \d                       digits (0-9)
----------------------------------------------------------------------
  \d?                      digits (0-9) (optional (matching the most
                           amount possible))
----------------------------------------------------------------------
  /                        '/'
----------------------------------------------------------------------
  \d                       digits (0-9)
----------------------------------------------------------------------
  \d                       digits (0-9)
----------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \d                       digits (0-9)
----------------------------------------------------------------------
    \d                       digits (0-9)
----------------------------------------------------------------------
  )?                       end of grouping
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------