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
240 views
in Technique[技术] by (71.8m points)

regex - Date Regular Expression in UNIX

I'm trying to write a regular expression to validate a date in Unix. The regex that matches a date in the usual format is mm/dd/yy

For example, it should match 03/20/98 or 11/08/89 but not 13/40/99

I managed to find the answer on Regular Expression to match valid dates but the expression is not working on UNIX.

Below regex is not working when I tried to validate the date

echo '12/01/2014' | grep '^((((0[13578])|([13578])|(1[02]))/)|(((0[469])|([469])|(11))/)|((2|02)/))[/]d{4}$|^d{4}$'

No matches

echo '2/1/2014' | grep '^((((0[13578])|([13578])|(1[02]))/)|(((0[469])|([469])|(11))/)|((2|02)/))[/]d{4}$|^d{4}$'

No matches

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are several regular expression formats; Probably you're trying to use standard or extended regular expressions, but using a PCRE from the linked answer.

And as the accepted answer there suggests, date validation is not easy with regular expressions alone. If an incomplete validation is acceptable to you, this simple one seems to pass my tests ( and note the use of egrep and not just grep for the (a|b) syntax:

for date in `cat dates.txt` ; do 
if (echo $date |
    egrep '^(1[0-2]|0[0-9])[-/]([0-2][0-9]|3[0-1])[-/][0-9]{2}' > /dev/null
); then 
       echo "$date is valid"
   else 
       echo "$date is invalid" 
   fi
done

Gives me:

01-01-48 is valid
13-01-99 is invalid
02-30-03 is valid
03-32-14 is invalid

But, as many have said on the other thread, the regular expression to verify number of days in a month and leap years becomes complicated fast. This regex only verifies that each part of the date is valid in itself - it doesn't verify that the day of the month exist in the month. That's why it thinks 02-30-03 is a valid date.


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

...