regex - 使用正则表达式模式验证 bash 中的用户输入时间

标签 regex bash shell time-format

假设用户进食时间:

read -p "Enter the start time you want to start(hh:mm:ss) " user_start_time

和正则表达式:

timePattern="[0-2][0-3]:[0-5][0-9]:[0-5][0-9]"

如果我这样做:

if [ "$user_start_time" == "$timePattern" ] 
#or if [ "$user_start_time" =~ "$timePattern" ]
then
         echo "in if"
else
         echo "in else"
fi

它不验证......作为新手,我理解 int 的比较或string但我们该怎么做time (日期也在那里,但是 date -d 解决了很多问题)

There is this question too 但无法理解接受的答案!!

最佳答案

对于正则表达式匹配,您需要在 BASH 中使用 =~ 运算符而不是 == 。所以像这样使用它:

[[ "$user_start_time" =~ $timePattern ]] && echo "in if" || echo "in else"

您还需要删除正则表达式变量周围的引号 $timePattern

关于regex - 使用正则表达式模式验证 bash 中的用户输入时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821920/

相关文章:

bash - Linux/庆典 : remove text between two chars

bash - 捕获 stderr,但不捕获 stdout

mysql - Ansible - 在 array 上循环由 shell 命令产生

shell - 如何使用 shell 将大文件拆分成多个部分

java - 使用正则表达式在 Java 中拆分字符串数组

regex - 用于正则表达式匹配的 Groovy 语法

javascript - 正则表达式将字符串转换为有效数字,无小数,符号可选

bash - 使用 cURL 下载目录中的所有文件

c++ - 如何将文件用作现有 C++ 程序的输入流?

RegEx 表达式以查找 href 链接并将 NoFollow 添加到它们