![我的正则表达式有什么问题?](https://linux22.com/image/112609/%E6%88%91%E7%9A%84%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%9C%89%E4%BB%80%E4%B9%88%E9%97%AE%E9%A2%98%EF%BC%9F.png)
#!/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