How to write a regex that checks alpha number and spaces

I am writing a bash validation function that degrades user input.

The idea is that if a script has 3 parameters, it can only be alpha-numeric values. BUT a parameter can be a few words enclosed in double quotes, for example:

myfunction arg1 arg2 "this is arg3"

So, I'm basically looking for everything that is not an alphanumeric or spatial symbol.

At the moment I have:

validateEntry() { string=$1 clean=${string//[^a-zA-Z0-9\s]/} }

But that does not work. In myfunction arg1 arg2 "this is arg3" the is arg3 element gets split.

And the way that I use this function is in a script, for example:

 name=$(validateEntry $1) 

I need help.

Edit

The idea is to use the validateEntry function in a script, which can take, say, 3 arguments, for example:

 if [[ "$#" -eq 3 ]]; then arg1=$(validateEntry $1) arg2=$(validateEntry $2) arg3=$(validateEntry $3) echo "${arg1}, ${arg2}, ${arg3}." fi 

But if my third script argument is this is arg3 , $arg3 comes down to this , although when I call my function directly with the same three arguments, the third arg this is arg3

+6
source share
2 answers

\s does not mean "any type of spaces" in the pattern (which is not a regular expression). Use either literal space instead

 clean=${1//[^a-zA-Z0-9 ]} 

or, if you want to combine spaces, tabs, newlines, etc., use the POSIX character class [:space:] :

 clean=${1//[^a-zA-Z0-9[:space:]]} 

(In this case, you can use character classes for letters and numbers:

 clean=${1//[^[:alnum:][:space:]]} 

)

Once you have done this, you need to change two things:

  • You need to output the cleared value:

     validateEntry () { echo "${1//[^[a[:alnum:][:space:]]}" } 
  • You need to specify the extension you want to check so that everything is passed to your function:

     name=$(validateEntry "$1") 
+5
source

Edited according to the question.

 function validateEntry { echo ${1//[^[:alnum:][:space:]]/} } if [[ $# -eq 3 ]]; then echo $(validateEntry "$1") echo $(validateEntry "$2") echo $(validateEntry "$3") fi 

Command

 ./test.sh arg1 arg2 "this is arg3" 

Output:

 arg1 arg2 this is arg3 
+2
source

All Articles