How to check if a string contains a special charac

2019-06-18 15:36发布

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.

标签: linux bash shell
5条回答
叛逆
2楼-- · 2019-06-18 15:44

Using expr

str='some text with @ in it'
if [ `expr "$str" : ".*[!@#\$%^\&*()_+].*"` -gt 0 ];
    then 
       echo "This str contain sspecial symbol"; 
       fi
查看更多
Emotional °昔
3楼-- · 2019-06-18 15:45

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 ]*$"

查看更多
疯言疯语
4楼-- · 2019-06-18 15:54

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
查看更多
虎瘦雄心在
5楼-- · 2019-06-18 15:54

You can also use a regexp:

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

There is nothing to escape because the special chars are in the single-quoted string; the [] means "anything in the contained string"; and because there is no ^ or $ in the pattern it will match anywhere in the $str.

查看更多
6楼-- · 2019-06-18 15:56

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

case $str in
  *['!'@#$%^&*()_+]* ) echo yup ;;
esac
查看更多
登录 后发表回答