Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a regex that validates alpha-numerics and spaces

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

The idea is that if a script has 3 parameters, those could be only alpha-numeric values. BUT a parameter could be multiple words enclosed in double quotes like so:

myfunction arg1 arg2 "this is arg3"

So I am basically looking to strip everything out that is not an alpha-numeric or space character.

At the moment, i've got:

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

But it does not seem to work. In myfunction arg1 arg2 "this is arg3", the is arg3 is getting stripped out.

And the way I am using this function is in a script, like so:

name=$(validateEntry $1)

I need help with that.

edit:

The idea is to use the validateEntry function in a script that can take, let's say, 3 arguments, like so:

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

But if my script's third argument is this is arg3, $arg3 is reduced to this, even though when i call my the function directly, with the same three arguments, the third arg is this is arg3

like image 766
Jeanmichel Cote Avatar asked Jul 31 '15 01:07

Jeanmichel Cote


2 Answers

\s does not mean "any type of whitespace" in a pattern (which is not a regular expression). Instead, either use just a literal space

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

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

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

(For that matter, you can use character classes for the letters and numbers as well:

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

)

Once you've done that, there are two other things you need to change:

  1. You need to actually output the cleaned-up value:

    validateEntry () {
       echo "${1//[^[a[:alnum:][:space:]]}"
    }
    
  2. You need to quote the expansion you want to validate, so that the entire thing is passed to your function:

    name=$(validateEntry "$1")
    
like image 190
chepner Avatar answered Sep 20 '22 04:09

chepner


Edited to match 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
like image 35
SArnab Avatar answered Sep 20 '22 04:09

SArnab