我需要验证日期格式,可以是11/11/11
或11/22/2013
,即年份块可以是YY
或YYYY
,完整格式将是MM/DD/YY
或MM/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
答案 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
----------------------------------------------------------------------