bash只允许带小数点的正整数或正整数

时间:2017-02-01 12:42:21

标签: bash

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

Output: It is not an integer

以上代码只能验证正整数。

如何允许带小数点的正整数?一直在网上搜索无济于事

2 个答案:

答案 0 :(得分:1)

以POSIX兼容的方式执行此操作非常棘手;您当前的模式与 - 整数匹配。两个bash扩展程序使这相当容易:

  1. 使用扩展模式

    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
    
  2. 使用正则表达式

    if [[ $price =~ ^[0-9]+(.?[0-9]*)$ ]]; then
        echo "It is an integer"
    else
        echo "Not an integer"
    fi
    
  3. (理论上,您应该能够使用POSIX命令expr进行正则表达式匹配;我无法使其正常工作,并且您没有指定POSIX兼容性作为要求所以我不会担心它.POSIX模式匹配不足以匹配任意长的数字串。)

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

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

答案 1 :(得分:-1)

试试这个正则表达式^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$

相关问题