bash只允许使用正整数或带小数点的正整数 [英] bash allow only positive integer or positive integer with decimal point

查看:104
本文介绍了bash只允许使用正整数或带小数点的正整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

price="1.11"
case $price in
            ''|*[!0-9]*) echo "It is not an integer.";
            ;;
        esac

Output: It is not an integer.

上面的代码仅能验证正整数.

The above code is able to verify positive integer only.

如何允许带小数点的正整数?已经通过互联网搜索无济于事

How do allow positive integer with decimal point? Have been searching through the internet to no avail

推荐答案

以与POSIX兼容的方式执行此操作很棘手.您当前的模式与 non 整数匹配.两个bash扩展名使此操作相当容易:

Doing this in a POSIX-compatible way is tricky; your current pattern matches non-integers. Two bash extensions make this fairly easy:

  1. 使用扩展模式

  1. Use extended patterns

shopt -s extglob
case $price in
    # +([0-9]) - match one or more integer digits
    # ?(.+([0-9])) - match an optional dot followed by zero or more digits
    +([0-9]))?(.*([0-9]))) echo "It is an integer" ;;
    *) echo "Not an integer"
esac

  • 使用正则表达式

  • Use a regular expression

    if [[ $price =~ ^[0-9]+(.?[0-9]*)$ ]]; then
        echo "It is an integer"
    else
        echo "Not an integer"
    fi
    

  • (从理论上讲,您还应该能够使用POSIX命令expr进行正则表达式匹配;我很难使其正常工作,并且您没有指定POSIX兼容性作为要求,因此我不必担心.POSIX模式匹配的功能不足以匹配任意长的数字字符串.)

    (In theory, you should be able to use the POSIX command expr to do regular expression matching as well; I'm having trouble getting it to work, and you haven't specified POSIX compatibility as a requirement, so I'm not going to worry about it. POSIX pattern matching isn't powerful enough to match arbitrarily long strings of digits.)

    如果只想匹配十进制"整数,而不是任意浮点值,那么它当然会更简单:

    If you only want to match a "decimalized" integer, rather than arbitrary floating point values, it is of course simpler:

    1. 扩展模式+([0-9])?(.)
    2. 正则表达式[0-9]+\.?
    1. The extended pattern +([0-9])?(.)
    2. The regular expression [0-9]+\.?

    这篇关于bash只允许使用正整数或带小数点的正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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