Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

regex - Pattern matching dates

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...