0

I need to check a string and make sure that it does not contain any character outside list of given characters.

I wrote one script to test this:

str="$1"

regex="^[0-9a-zA-Z\,\!\-\^\`@\{\}\[\],=\(\).;\/~_|]*$"

if [[ "$str" =~ $regex ]]
then
  echo "f yeah"
else
  echo "f you"
fi

But it does not seem to work. And it seems to me that I am not even close.

List of allowed characters is :

a-z A-Z 0-9 ` @ { } [ ] ^ , = ! ( ) . ; / ~ _ |

Not sure what I am missing here.

1
  • 2
    How do you mean "does not seem to work"? Do you get an error? What is your output? Are you simply never matching? Always matching? What are you passing it as an argument? – Centimane Nov 24 '15 at 15:22
5

You can't include a ] into a character class by backslashing it. It must be the first element in the class. The same holds for the dash, but this time, it must go last. \-\^ just matches the range from \ to \, i.e. the backslash, and the caret. (I removed useless backslashes, too).

regex='^[]0-9a-zA-Z,!^`@{}=().;/~_|[-]*$'

Are you sure you want *, not +? Do you really want to accept empty strings?

2
  • Is there any way to get character that did not match? Example if I pass 12$, it shall return $ – codingenious Nov 24 '15 at 17:04
  • 1
    @Batty: Better to ask this as a new question. – choroba Nov 24 '15 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.