Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm having troubles trying to match a pattern of dates. Any of the following dates are legal:

 - 121212
 - 4 9 12
 - 5-3-2000
 - 62502
 - 3/3/11
 - 09-08-2001
 - 8 6 07
 - 12 10 2004
 - 4-16-08
 - 3/7/2005

What makes this date matching really challenging is that the year doesn't have to be 4 digits (a 2 digit year is assumed to be in the 21st century i.e. 02 = 2002), the month/date can either be written with a beginning 0 if it is a one digit month, and the dates may or may not be separated by spaces, dashes, or slashes.

This is what I currently have:
/((((0[13578])|([13578])|(1[02]))[/-]?s*(([1-9])|(0[1-9])|([12][0-9])|(3[01])))|(((0[469])|([469])|(11))[/-]?s*(([1-9])|(0[1-9])|([12][0-9])|(30)))|((2|02)[/](([1-9])|(0[1-9])|([12][0-9])))[/-]?s*(20[0-9]{2})|([0-9]{2}))/g

This almost works, except right now I'm not exactly sure if I'm assuming the length of the dates and months. For example, in the case 121212, I might be assuming the month is 1 instead of 12. Also, for some reason when I'm printing out $1 and $2, it is the same value. In the case of 121212, $1 is 1212, $2 is 1212 and $3 is 12. However, I just want $1 to be 121212.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your task is ambiguous, since you may not be able to tell mmd from mdd or mdccyy from mmddyy.

You left off the option for spaces or dashes in one place where you match /.

You aren't checking for leap years.

This is doable, but it's awfully easy to make a mistake; how about not trying to do it with a regex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...