测试字符串是否为有效整数 [英] Test whether string is a valid integer
问题描述
我正在尝试做一些足够常见的事情:在 shell 脚本中解析用户输入.如果用户提供了一个有效的整数,脚本会做一件事,如果无效,它会做其他事情.问题是,我还没有找到一种简单(且相当优雅)的方法来做到这一点 - 我不想逐个字符地将它分开.
I'm trying to do something common enough: Parse user input in a shell script. If the user provided a valid integer, the script does one thing, and if not valid, it does something else. Trouble is, I haven't found an easy (and reasonably elegant) way of doing this - I don't want to have to pick it apart char by char.
我知道这一定很容易,但我不知道该怎么做.我可以用十几种语言来做,但不能用 BASH!
I know this must be easy but I don't know how. I could do it in a dozen languages, but not BASH!
在我的研究中,我发现了这一点:
In my research I found this:
其中有一个关于正则表达式的答案,但据我所知,这是 C 中可用的函数(以及其他函数).尽管如此,它的答案看起来不错,所以我用 grep 尝试了它,但 grep 不知道如何处理它.我试过 -P 在我的盒子上意味着把它当作一个 PERL 正则表达式 - nada.Dash E (-E) 也不起作用.-F 也没有.
And there's an answer therein that talks about regex, but so far as I know, that's a function available in C (among others). Still, it had what looked like a great answer so I tried it with grep, but grep didn't know what to do with it. I tried -P which on my box means to treat it as a PERL regexp - nada. Dash E (-E) didn't work either. And neither did -F.
明确地说,我正在尝试这样的事情,寻找任何输出 - 从那里,我将修改脚本以利用我得到的任何东西.(IOW,我原以为在重复有效行时,不符合要求的输入不会返回任何内容.)
Just to be clear, I'm trying something like this, looking for any output - from there, I'll hack up the script to take advantage of whatever I get. (IOW, I was expecting that a non-conforming input returns nothing while a valid line gets repeated.)
snafu=$(echo "$2" | grep -E "/^[-+]?(?:.[0-9]+|(?:0|[1-9][0-9]*)(?:.[0-9]*)?)$/")
if [ -z "$snafu" ] ;
then
echo "Not an integer - nothing back from the grep"
else
echo "Integer."
fi
有人能说明这是最容易做到的吗?
Would someone please illustrate how this is most easily done?
坦率地说,在我看来,这是 TEST 的一个缺点.它应该有一个这样的标志
Frankly, this is a short-coming of TEST, in my opinion. It should have a flag like this
if [ -I "string" ] ;
then
echo "String is a valid integer."
else
echo "String is not a valid integer."
fi
推荐答案
[[ $var =~ ^-?[0-9]+$ ]]
^
表示输入模式的开始-
是文字-"?
表示前面 (-
) 的 0 或 1"+
表示1 个或多个前面的 ([0-9]
)"$
表示输入模式的结束- The
^
indicates the beginning of the input pattern - The
-
is a literal "-" - The
?
means "0 or 1 of the preceding (-
)" - The
+
means "1 or more of the preceding ([0-9]
)" - The
$
indicates the end of the input pattern
所以正则表达式匹配一个可选的-
(对于负数的情况),后跟一个或多个十进制数字.
So the regex matches an optional -
(for the case of negative numbers), followed by one or more decimal digits.
参考资料:
这篇关于测试字符串是否为有效整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!