测试string是否为有效整数 [英] Test whether string is a valid integer

查看:108
本文介绍了测试string是否为有效整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些常见的事情:在shell脚本中解析用户输入。如果用户提供了有效的整数,则脚本会执行一项操作,如果无效,则执行其他操作。麻烦的是,我没有找到一种简单(而且相当优雅)的方式 - 我不想让它通过char选择它。

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:

正则表达式测试一个字符串是否包含基数10中的有效实数

其中有一个关于正则表达式的答案,但据我所知,这是C(以及其他)中可用的功能。尽管如此,它看起来像是一个很好的答案,所以我尝试用grep,但grep不知道该怎么做。我试过-P在我的盒子上意味着把它当作PERL regexp - 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( -

  • + 表示前面的一个或多个(<$ c) $ c> [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.

      参考文献

      • http://www.tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

      这篇关于测试string是否为有效整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆