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.
@#$%^&*.,<>/\'";:? and return true if the string contains atleast one of those chars. If the string contains only the special characters then it returns true , but if the string contains something else like alphanumeric chars ( ! example1 , . example2 ) it returns false.
Use it inside for loop and check or the string that has special characters. str. ToCharArray(); With that, use a for loop and to check for each character using the isLetterOrDigit() method.
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
You can also use a regexp:
if [[ $str =~ ['!@#$%^&*()_+'] ]]; then
echo yes
else
echo no
fi
Some notes:
$str =~ '[!...+]'
would not work). []
means "anything in the contained string"^
or end with $
there will be a match anywhere in the $str
. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With