Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 检查字符串中的符号时出现错误?_Linux_Bash_Shell_Ubuntu - Fatal编程技术网

Linux 检查字符串中的符号时出现错误?

Linux 检查字符串中的符号时出现错误?,linux,bash,shell,ubuntu,Linux,Bash,Shell,Ubuntu,我正在创建一个小的计算器脚本,我偶然发现了一个奇怪的错误。一切似乎都正常,但当我输入任何以()开头的内容时就不行了。当我输入时,如果给出false,那么中的代码就会执行。我尝试了很多方法重写“$input”=~[-,+,*,/,\(,\)]看起来很像,但没有任何效果。您知道为什么会出现这种情况以及如何解决此错误吗 #!/bin/bash read -p "Input: " input if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~

我正在创建一个小的计算器脚本,我偶然发现了一个奇怪的错误。一切似乎都正常,但当我输入任何以
)开头的内容时就不行了。当我输入
时,如果
给出false,那么
中的代码就会执行。我尝试了很多方法重写
“$input”=~[-,+,*,/,\(,\)]
看起来很像,但没有任何效果。您知道为什么会出现这种情况以及如何解决此错误吗

#!/bin/bash
read -p "Input: " input
if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~ ^[0-9] && "$input" =~ [-,+,*,/,\(,\)] ]]; then
 (echo $input = $(($input))) 2>- || echo "Please, do not input ..."
else
 echo "Please, do not input letters or other special symbols and type in only expressions."
fi
  • …当我输入任何以
    )开头的内容时。如果

    这是因为第二个测试要求表达式以数字开头:当表达式以
    )开头时,测试
    “$input”=~^[0-9]
    失败

  • [-,+,*,/,\(,\)]
    可以简化为
    [-,+*/()]
    。这是因为(a)不需要在
    […]
    中转义参数,并且(b)没有理由在方括号表达式中指定
    五次,
    […]
    。如果希望正则表达式与逗号匹配,只需列出一次即可。如果不希望正则表达式与逗号匹配,请不要将逗号放在
    […]


  • 如果需要确保输入仅由某些字符组成,请使用更简单的正则表达式:

    #!/bin/bash
    
    read -r -p "Input: " input
    
    if [[ $input =~ ^[0-9+*/()-]*$ ]]; then
       (echo "$input = $((input))") 2> /dev/null || echo "Please, do not input ..."
    else
       echo "Please, do not input letters or other special symbols and type in only expressions."
    fi
    

    你试过删除后斜杠吗?我在括号前面?我想,在字符匹配中,你不应该需要这些。请注意:字符类中字符之间没有分隔符。(如果只是想把其他字母分开,也许根本就不应该有一个
    。。一个在OP上要抛回的问题。)@user2864740非常好。我编辑了答案,以便在这一点上更清楚。非常感谢你的回答,我会考虑它。