2

I have this code with regular expression:

read string

regex="^[1-9][0-9]*\+[1-9][0-9]+$"

if [[ "$string" =~ $regex ]]; then

  echo "it's ok"

fi

Regular expression works for me, but when I insert a string with initial space , for example " 9+2", it should not recognize it(because in the regex I say it that the string must start with a number and not a space) but it print "it's ok" although it should not.

Why? what wrong in this code?

Alex
  • 89
  • 1
  • 2
  • 9

2 Answers2

2

One problem is that read removes the initial spaces so when the regex runs the value of $string is just 9+2 with no initial space. If you set the $string variable directly in your script instead of using userinput using read it should work.

More info on read's behavior at the following stackoverflow question:

Bash read line does not read leading spaces

Community
  • 1
  • 1
bdk
  • 4,769
  • 29
  • 33
2

If you want read to keep leading and trailing spaces, then you need to set IFS to empty:

IFS= read string
regex="^[0-9]+\+[0-9]+$"
if [[ "$string" =~ $regex ]]; then
  echo "it's ok"
fi

In the above, I also corrected the ~= operator and modified the regex to agree with your examples.

The behavior of read can be seen more directly in the following examples:

$ echo " 9+2 " | { read s; echo ">$s<"; }
>9+2<
$ echo " 9+2 " | { IFS= read s; echo ">$s<"; }
> 9+2 <
John1024
  • 109,961
  • 14
  • 137
  • 171