Alex
Alex

Reputation: 89

Regular expression Bash

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?

Upvotes: 2

Views: 167

Answers (2)

John1024
John1024

Reputation: 113814

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 <

Upvotes: 2

bdk
bdk

Reputation: 4839

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

Upvotes: 2

Related Questions