deadcell4
deadcell4

Reputation: 6725

How to check if a string contains a special character (!@#$%^&*()_+)

I was wondering what would be the best way to check if a string as

$str 

contains any of the following characters

!@#$%^&*()_+

I thought of using ASCII values but was a little confused on exactly how that would be implemented.

Or if there is a simpler way to just check the string against the values.

Upvotes: 16

Views: 71880

Answers (5)

tripleee
tripleee

Reputation: 189658

This is portable to Dash et al. and IMHO more elegant.

case $str in
  *['!&()'@#$%^*_+]* ) echo yup ;;
esac

Upvotes: 10

Oliver
Oliver

Reputation: 29571

You can also use a regexp:

if [[ $str =~ ['!@#$%^&*()_+'] ]]; then
    echo yes
else
    echo no
fi

Some notes:

  • The regexp includes the square brackets
  • The regexp must not be quoted (so $str =~ '[!...+]' would not work).
  • There is no need to escape chars as is necessary with the glob approach in another answer, because the chars are between the brackets, where they are taken literally by regexp
  • as with glob pattern [] means "anything in the contained string"
  • because the pattern does not start with ^ or end with $ there will be a match anywhere in the $str.

Upvotes: 7

R. Kumar
R. Kumar

Reputation: 109

I think one simple way of doing would be like remove any alphanumeric characters and space.

echo "$str" | grep -v "^[a-zA-Z0-9 ]*$"

If you have a bunch of strings then put them in a file like strFile and following command would do the needful.

cat strFile | grep -v "^[a-zA-Z0-9 ]*$"

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19753

Using expr

str='some text with @ in it'
if [ `expr "$str" : ".*[!@#\$%^\&*()_+].*"` -gt 0 ];
    then 
       echo "This str contain sspecial symbol"; 
       fi

Upvotes: 1

that other guy
that other guy

Reputation: 123570

Match it against a glob. You just have to escape the characters that the shell otherwise considers special:

#!/bin/bash
str='some text with @ in it'
if [[ $str == *['!'@#\$%^\&*()_+]* ]]
then
  echo "It contains one of those"
fi

Upvotes: 39

Related Questions