String regex comparisons

Here is the sample code:

str1="abccccc"
str2="abc?"
if [[ $str1 =~ $str2 ]]; then
  echo "same string"
else
  echo "different string"
fi

Given that ? implies 0 or 1 match of preceding character, I was expecting the output to be "different string", but I am seeing "same string".

Am I not using the regex comparisons in right way?

thanks,
RCK

try it with quotes around your variables;

if [[ "$str1" =~ "$str2" ]]; then

ongoto: No. Quoting $str2 in this context performs a string comparison instead of an ERE match.

Rameshck: The ERE abc? will match ab or abc appearing anywhere in the expansion of $str1 . To match only ab or abc you need to anchor the ERE on both ends:

str1="abccccc"
str2='^abc?$'
if [[ $str1 =~ $str2 ]]; then
  echo "same string"
else
  echo "different string"
fi
1 Like

@ Don Cragun
Aha!
I find that ...

Good catch! Thanks.

1 Like