#!/bin/sh
REGEX="^[2][0-2]:[0-5][0-9]$"
TIME="21:30"
if [ $TIME = $REGEX ]; then
echo "Worked"
else
echo "Did not work"
fi
我想这与 : 有关,但就我而言,这只是一个不需要转义序列的常规标志。
答案1
简单的=
正则表达式比较是错误的。您必须使用=~
, 并且还必须使用双括号:
if [[ $TIME =~ $REGEX ]]; then
...
也可以看看:https://stackoverflow.com/questions/17420994/bash-regex-match-string
答案2
您还可以查看以下case
声明:
REGEX="[2][0-2]:[0-5][0-9]"; # Note no placeholders like ^ and $ here
TIME="21:30"
case $TIME in
$REGEX ) echo "Worked" ;; # Note no double quotes around $REGEX for allowing the wildcard matching to happen
* ) echo "Did not work" ;;
esac