xralf
xralf

Reputation: 3662

Test if a string contains only whitespace and non-alphanumeric characters

I tried the following solution.

if !(($str =~ ^.*[a-zA-Z0-9].*$)); then
  continue;
fi

It seems there's something wrong with the syntax.

Upvotes: 1

Views: 1387

Answers (2)

anubhava
anubhava

Reputation: 785276

Both your regex and syntax is incorrect. You need not use regex at all, just need glob for this:

checkStr() {
   [[ $1 != *[a-zA-Z0-9]* ]]
}

This will return false if even one alphanumeric is found in the input. Otherwise true is returned.

Test it:

$> if checkStr 'abc'; then
   echo "true case"
else
   echo "false case"
fi    
false case

$> if checkStr '=:() '; then
   echo "true case"
else
   echo "false case"
fi
true case

$> if checkStr '=:(x) '; then
   echo "true case"
else
   echo "false case"
fi
false case

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158050

You can use the [:alnum:] character class. I'm negating using the ^:

if [[ "${str}" =~ ^[^[:alnum:]]$ ]] ; then
    echo "yes"
fi

Upvotes: 1

Related Questions