我试图在ksh中验证输入,并且想知道确定字符串是否是有效数字的最简单方法。
laik7k3q1#
试试看:
case $INPUT in +([0-9])*(.)*([0-9]) ) # Variable is numeric ;; *) # Nope, not numeric ;; esac
字符串
ef1yzkbh2#
更简单,如果你只是想知道字符串是否由数字组成:
case $INPUT in [0-9][0-9]* ) # Variable contains only digits ;; *) # Variable contains at least one non-digit ;; esac
pgpifvop3#
我在这里看到了这个答案(https://www.unix.com/302299284-post9.html),它在Solaris 10的ksh-88中对整数有效:
x=2763 if [[ $x == +([0-9]) ]]; then print integer else print nope fi
wvmv3b1j4#
这修复了FreudianSlip的答案,以包括可选的前导“-”或“+”符号,允许以“.”开始的十进制数字(没有前导0),并排除包含多个“.”的数字(例如。“12...34”):
case $INPUT in {,1}([-+])+([0-9]){,1}(.)*([0-9])|{,1}([-+]).+([0-9])) # Variable is numeric ;; *) # Nope, not numeric ;; esac
bakd9h0s5#
你可以在测试中使用字符串操作符,如下所示:
if [[ "${input%%*( )+([0-9])?(.)*([0-9])}" = "" ]]; then print "Is numeric" fi
nhjlsmyf6#
[ $input -ge 0 -o $input-lt 0 ] 2>/dev/null && echo "numeric"
字符串这将检查输入是否是数字(正整数或负整数),如果是,则打印数字。
q5iwbnjs7#
if [[ -z $(print $input | tr -d '[:digit:]') ]] then print "$input is numeric" fi
字符串-z测试运算符用于测试空字符串。tr -d命令删除所有数字。如果在tr之后还有任何剩余,则它不是数字。
tr -d
7条答案
按热度按时间laik7k3q1#
试试看:
字符串
ef1yzkbh2#
更简单,如果你只是想知道字符串是否由数字组成:
字符串
pgpifvop3#
我在这里看到了这个答案(https://www.unix.com/302299284-post9.html),它在Solaris 10的ksh-88中对整数有效:
字符串
wvmv3b1j4#
这修复了FreudianSlip的答案,以包括可选的前导“-”或“+”符号,允许以“.”开始的十进制数字(没有前导0),并排除包含多个“.”的数字(例如。“12...34”):
字符串
bakd9h0s5#
你可以在测试中使用字符串操作符,如下所示:
字符串
nhjlsmyf6#
字符串
这将检查输入是否是数字(正整数或负整数),如果是,则打印数字。
q5iwbnjs7#
字符串
-z测试运算符用于测试空字符串。
tr -d
命令删除所有数字。如果在tr之后还有任何剩余,则它不是数字。