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 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

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

1 Answer

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.


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