简体   繁体   English

Bash验证日期格式

[英]Bash Verify date format

I try to check, if input is correct. 我尝试检查输入是否正确。 The input is correct if looks like YYYY-MM-DD. 如果看起来像YYYY-MM-DD,则输入正确。 I try to write a function, but I get failed result. 我尝试编写一个函数,但结果失败。

function reg_exp 
{
    if [[ $1 =~ [0-9]{4}-[0-9]{2}-[0-9]{2} ]]
    then echo "true"
    else echo "false"
    fi
}

>reg_exp 2015-10-20
true

# but for the parameter "2015-10-200" the results is failed....
> reg_exp 2015-10-200
true

Where is the mistake? 错误在哪里?

You are checking only that that pattern exists in your input. 您仅在检查输入中是否存在该模式。 To check that the pattern is all of the input, try: 要检查模式是否为所有输入,请尝试:

function reg_exp 
{
    if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
    then echo "true"
    else echo "false"
    fi
}

The ^ means beginning of string and the $ means end of string. ^表示字符串的开头, $表示字符串的结尾。

As your format matches the one of date , you can use it to validate your date instead of using a regex. 由于您的格式与date之一匹配,因此您可以使用它来验证日期,而不必使用正则表达式。 It will check for leap years and specific number of days per month : 它将检查leap年和每月的特定天数:

check_date() {
    if date -d "$1" &>/dev/null
        then echo true
    else
         echo false
    fi
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM