UNIX中的日期正则表达式 [英] Date Regular Expression in UNIX

查看:85
本文介绍了UNIX中的日期正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写正则表达式来验证 Unix 中的日期.与通常格式的日期匹配的正则表达式为mm/dd/yy

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

例如,它应匹配03/20/98或11/08/89,但不匹配13/40/99

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

我设法找到了正则表达式以匹配有效日期的答案但是该表达式在UNIX上不起作用.

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} $'

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

没有匹配项

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

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

没有匹配项

推荐答案

有几种正则表达式格式.可能您正在尝试使用标准或扩展正则表达式,但使用链接答案中的PCRE.

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.

并且正如公认的答案所暗示的那样,仅使用正则表达式并不容易实现日期验证.如果您接受不完整的验证,那么这个简单的验证似乎可以通过我的测试(请注意, egrep 的使用,而不仅仅是 grep 用于(a |b)语法:

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

给我:

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

但是,正如许多人在其他主题上所说的那样,用于验证一个月中的天数和leap年的正则表达式很快变得很复杂.此正则表达式仅验证日期的每个部分本身是否有效-不会验证月份中是否存在月份中的某天.这就是为什么它认为 02-30-03 是有效日期.

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.

这篇关于UNIX中的日期正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆