Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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.

like image 659
deadcell4 Avatar asked Oct 29 '14 02:10

deadcell4


People also ask

How do you check if a string has special characters in JS?

@#$%^&*.,<>/\'";:? 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.

How do you check if a string contains any special character in C#?

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.


2 Answers

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
like image 50
that other guy Avatar answered Oct 23 '22 11:10

that other guy


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.
like image 25
Oliver Avatar answered Oct 23 '22 09:10

Oliver