Bash RegEx可以检查用户输入中的浮点数 [英] Bash RegEx to check floating point numbers from user input

查看:65
本文介绍了Bash RegEx可以检查用户输入中的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash编程还比较陌生,目前正在创建一个简单的计算器.

I'm relatively new to bash programming and i am currently creating a simple calculator.

它需要使用浮点数并检查它们是否正确.

It needs to use floating point numbers and check they are so.

我有一个checkNumbers函数:

I have a checkNumbers function:

function checkNumber {

    regExp=[0-9]

    if [ $testNo =~ $regExp ]
    then
        echo "That is a number!"
        let check=1
    else
        echo "Damn! Not A Number!"
    fi
}

我让用户输入这样的数字:

where i get the user to input a number like this:

while [ $check -eq 0]
do
    echo "Please enter a number
    read testNo
    echo ""
    checkNumber
done

这不起作用,我收到此错误:

This does not work, i get this error:

./calculator.sh:第39行:[:=〜:预期为二进制运算符

./calculator.sh: line 39: [: =~: binary operator expected

第39行是:

if [ $testNo =~ $regExp ] 

我尝试了很多正则表达式,例如:

I have tried lots of Regular Expressions like:

^*[0-9]*$

^*[0-9]\.[0.9]*$

等等等

另外,我还捆绑了执行检查的其他方式:

also, i have tied other ways of performing the check:

case $testNo
in
    ^*[0-9]*$) echo "That is a number!";;
    *) echo "Error! Not a number!";;
esac

if [ $testNo = ^*[0-9]*$ ]
then
    echo "etc etc"
else
    echo "oops"
fi

我还需要使用它来处理浮点数.

I also need this to work with floating point numbers.

有人可以让我知道我该怎么做吗?

could someone please let me know how i go about this?

推荐答案

此正则表达式 ^ [-+]?[0-9] + \.?[0-9] * $ 将匹配只有带有可选的数字.:

This regex ^[-+]?[0-9]+\.?[0-9]*$ will match only digits with an optional .:

$ echo 30 | grep -Eq '^[-+]?[0-9]+\.?[0-9]*$' && echo Match
Match

$ echo 30.10 | grep -Eq '^[-+]?[0-9]+\.?[0-9]*$' && echo Match
Match

$ echo 30. | grep -Eq '^[-+]?[0-9]+\.?[0-9]*$' && echo Match
Match

$ echo +30 | grep -Eq '^[-+]?[0-9]+\.?[0-9]*$' && echo Match
Match

$ echo -30 | grep -Eq '^[-+]?[0-9]+\.?[0-9]*$' && echo Match
Match

我认为当您尝试 ^ * [0-9] 时,您想要的是 ^ [0-9] *

I think when you tried ^*[0-9] you wanted ^[0-9]*

重新布置:

^       # Match start of string
[-+]?   # Match a leading + or - (optional)
[0-9]+  # Match one or more digit
\.?     # Match a literal . (optional, escaped)
[0-9]*  # Match zero or more digits
$       # Match the end of the string

注意:这会匹配数字,后跟一个.,例如 30.,不确定是否可以接受.

Note: this matches numbers followed by a . like 30., not sure if this is acceptable for you.

不要引用 regex

testNo=30.00

if [[ $testNo =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; then 
    echo Match
fi

>>> Match

这篇关于Bash RegEx可以检查用户输入中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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