我想使用正则表达式检查变量是否具有有效年份。阅读bash manual我知道我可以使用运算符 =~
查看下面的示例,我希望看到“不正常”,但我看到“正常”。我做错了什么?
i="test"
if [ $i=~"200[78]" ]
then
echo "OK"
else
echo "not OK"
fi
最佳答案
它在 3.1 和 3.2 之间发生了变化:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
因此在不带引号的情况下使用它:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
关于regex - 如何在 bash 脚本中使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/304864/