Home Bug while checking for symbols inside of a string?
Reply: 2

Bug while checking for symbols inside of a string?

nexusgeniuz
1#
nexusgeniuz Published in 2017-12-07 23:44:12Z

I'm creating a small calculator script and I've got stumbled on a strange bug. Everything seems to work but not when I input anything starting with (. When I do that if gives false and the code inside of else executes. I've tried a lot of ways rewriting how should "$input" =~ [-,+,*,/,\(,\)] look like but nothing worked. Do you have any idea why that's happening and how to solve this bug?

#!/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
PesaThe
2#
PesaThe Reply to 2017-12-08 10:42:36Z

If you need to make sure your input consists of just certain characters, use this much simpler regex:

#!/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
John1024
3#
John1024 Reply to 2017-12-08 00:18:30Z
  1. ...when I input anything starting with (. When I do that if gives false

    That is because the second test requires that expressions start with a number: when an expression starts with (, the test "$input" =~ ^[0-9] fails.

  2. [-,+,*,/,\(,\)] can be simplified to [-,+*/()]. This is because (a) the parens do not need to be escaped inside [...], and (b) there is no reason to specify , five times within a square bracket expression, [...]. If you want the regex to match a comma, listing it once is sufficient. If you don't want it to match a comma, don't put the comma inside [...].

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.432678 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO