4

我需要验证日期格式,可以是11/11/11or 11/22/2013,即年份块可以是YYor YYYY,完整格式将是MM/DD/YYorMM/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 应用它

4

2 回答 2

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

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

于 2013-08-26T12:20:26.663 回答
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
----------------------------------------------------------------------
于 2013-08-26T12:34:01.360 回答