gpt4 book ai didi

regex - 如何在 bash 脚本中使用正则表达式?

转载 作者:行者123 更新时间:2023-11-29 08:39:15 25 4
gpt4 key购买 nike

我想使用正则表达式检查变量是否具有有效年份。阅读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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com