bash allow only positive integer or positive integer with decimal point

后端 未结 2 1164
慢半拍i
慢半拍i 2021-01-27 21:39
price=\"1.11\"
case $price in
            \'\'|*[!0-9]*) echo \"It is not an integer.\";
            ;;
        esac

Output: It is not an integer

相关标签:
2条回答
  • 2021-01-27 22:10

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

    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
      
    2. Use a regular expression

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

    (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. The extended pattern +([0-9])?(.)
    2. The regular expression [0-9]+\.?
    0 讨论(0)
  • 2021-01-27 22:28

    Try this regular expression ^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$

    0 讨论(0)
提交回复
热议问题