我的脚本收到的参数之一是以下格式的日期:yyyymmdd
。
我想检查输入的日期是否有效。
我怎样才能做到这一点?我正在尝试使用如下正则表达式:[0-9]\{\8}
您可以使用测试构造[[ ]]
以及正则表达式匹配运算符=~
来检查字符串是否与正则表达式模式匹配。
对于您的特定情况,您可以编写:
[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
或更准确的测试:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
# | | ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ |
# | | | | |
# | | \ | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 end of line
# start of line or 10,11,12 or 10..29
# or 30, 31
也就是说,您可以在Bash中定义与所需格式匹配的正则表达式。这样,您可以执行以下操作:
[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
其中命令之后&&
被执行,如果测试是成功的,和命令之后||
,如果测试不成功被执行。
请注意,这是基于Aleks-Daniel Jakimenko在bash中的用户输入日期格式验证中的解决方案。
在其他Shell中,可以使用grep。如果您的外壳符合POSIX,请执行
(echo "$date" | grep -Eq ^regex$) && echo "matched" || echo "did not match"
在不符合POSIX的fish中,您可以执行
echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句