哇。我真的怀疑一个正则表达式是去这里的方式......但是,让我们尝试一下。
首先重新格式化正则表达式以使其更具可读性。如您所见,它由许多替代方案组成。添加评论:
/^
(
(
((0?[1-9]|[12]\d|3[01])-/-/) # dd-/-/
|
((0?[1-9]|[12]\d|30)-/-/) # dd-/-/ (uh, this seems redundant?)
|
((0?[1-9]|1\d|2[0-8])[-/]0?2-/) # dd-/-/ (february)
|
(29[-/]0?2-/)
)
|
(
(
(0[1-9]|[12]\d|3[01]) # day
(0[13578]|1[02]) # month
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
(0[1-9]|[12]\d|30) # day
(0[13456789]|1[012]) # month
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
(0[1-9]|1\d|2[0-8]) # day
02 # month
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
2902 # day and month
( # year in which there's a 29-02-xxxx
(1[6-9]|[2-9]\d)?
(0[48]|[2468][048]|[13579][26])
|
((16|[2468][048]|[3579][26])00)
|
00
)
)
)
)
$/i
接下来,重新排序正则表达式以将其从 ddmmyyyy 更改为 mmddyyyy:
/^
(
(
(-/(0?[1-9]|[12]\d|3[01])-/) # -/dd-/
|
(-/(0?[1-9]|[12]\d|30)-/) # -/dd-/ (uh, this seems redundant?)
|
([-/]0?2(0?[1-9]|1\d|2[0-8])-/) # -/dd-/ (february) (I don't really get this one...)
|
([-/]0?229-/) # really confused... what kind of date format is this?
)
|
(
(
(0[13578]|1[02]) # month
(0[1-9]|[12]\d|3[01]) # day
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
(0[13456789]|1[012]) # month
(0[1-9]|[12]\d|30) # day
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
02 # month
(0[1-9]|1\d|2[0-8]) # day
((1[6-9]|[2-9]\d)?\d{2}) # year
)
|
(
0229 # day and month
( # year in which there's a 29-02-xxxx
(1[6-9]|[2-9]\d)?
(0[48]|[2468][048]|[13579][26])
|
((16|[2468][048]|[3579][26])00)
|
00
)
)
)
)
$/i
请注意,我对包含的日期格式感到非常困惑,-/
因此可能无法正确重写它们。
然后将其放入您的代码中。如果您不希望有人死于致命剂量的不可读的正则表达式,请保留注释(如果您的编程语言允许这样做)。