1

I tried the following solution.

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

It seems there's something wrong with the syntax.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

I need the expression that returns True if a string matches a mix of zero or more whitespace and zero or more non-alphanumeric characters. If there is at least one alpha-numeric character it should return False. That's because I find the opposite and then negate the result with !
@xralf The != operator here does that, unless you have a specific set of nonalphanumeric characters in mind.
@anubhava The examples you provided are exactly what I thought.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.