Bash 比较检查仅接受格式为 0.1 的值
Bash comparison check to accept values only with format 0.1
我有这个片段:
if [[ =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; then
echo 'version is good'
exit 0
else
exit 1
fi
问题是,片段 =~ ^[+-]?[0-9]+\.?[0-9]*$
应该只验证格式为 number.number
的版本
目前这段代码将输入验证为
1
01
0.1
有没有办法让代码只接受格式为 0.1 / 0.3.2 / 0.1.141
等的输入
提前致谢。
编辑:
为了澄清这个问题,代码应该只接受用点分隔的数字,就像软件程序版本控制一样。
我建议这个正则表达式:^[0-9]+(\.[0-9]+){1,2}$
我建议不用正则表达式 :
[[ "0" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "01" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "0.1" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.3.2" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
To clarify this question, the code should only accept numbers
separated with dots, like software program versioning.
[[ "0" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "01" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "0.1" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.3.2" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK
我有这个片段:
if [[ =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; then
echo 'version is good'
exit 0
else
exit 1
fi
问题是,片段 =~ ^[+-]?[0-9]+\.?[0-9]*$
应该只验证格式为 number.number
目前这段代码将输入验证为
1
01
0.1
有没有办法让代码只接受格式为 0.1 / 0.3.2 / 0.1.141
等的输入
提前致谢。
编辑:
为了澄清这个问题,代码应该只接受用点分隔的数字,就像软件程序版本控制一样。
我建议这个正则表达式:^[0-9]+(\.[0-9]+){1,2}$
我建议不用正则表达式 :
[[ "0" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "01" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "0.1" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.3.2" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == ?([+-])+([0-9]).+([0-9.]) ]] && echo OK # OK
To clarify this question, the code should only accept numbers separated with dots, like software program versioning.
[[ "0" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "01" == +([0-9]).+([0-9.]) ]] && echo OK # Nothing
[[ "0.1" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.3.2" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "0.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK
[[ "10.1.141" == +([0-9]).+([0-9.]) ]] && echo OK # OK