bash Shell REGEX 表示日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36948220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell REGEX for date
提问by swag antiswag
I am trying to fix the users input if they input an incorrect date format that is not (YYYY-MM-DD) but I cant figure it out. Here is what I have:
如果用户输入的日期格式不正确(YYYY-MM-DD),我正在尝试修复用户输入,但我无法弄清楚。这是我所拥有的:
while [ "$startDate" != "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ]
do
echo "Please retype the start date (YYYY-MM-DD):"
read startDate
done
回答by fedorqui 'SO stop harming'
Instead of !=
, you have to use ! $var =~ regex
to perform regex comparisons:
取而代之的是!=
,您必须使用! $var =~ regex
来执行正则表达式比较:
[[ $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
^^
So that your script can be like this:
这样你的脚本就可以是这样的:
date=""
while [[ ! $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; do
echo "enter date (YYYY-MM-DD)"
read $date
done
回答by Wei Shen
Why not convert the incorrect format to desired one using date program:
为什么不使用日期程序将不正确的格式转换为所需的格式:
$ date -d "06/38/1992" +"%Y-%m-%d"
1992-06-28
You can also check for conversion failure by checking return value.
您还可以通过检查返回值来检查转换失败。
$ date -d "06/38/1992" +"%Y-%m-%d"
date: invalid date ‘06/38/1992'
$ [ -z $? ] || echo "Error, failed to parse date"