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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…