Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if the string also starts and ends with a space in shell script?

How to verify if the string also starts and ends with one or more space(s) ?

if [[ $username =~ [^0-9A-Za-z]+ ]]

(basically input should be alphanumeric, no spaces anywhere, even in the beginning or in the end, and no commas, underscores, hiphens etc)

The above regex unfortunately does NOT match leading & trailing spaces, but it matches spaces in between ?

Without awk, sed, is there any way I can fix the above regex to match leading & trailing spaces also ?

Thanks in advance

like image 356
Sandeep Avatar asked Oct 28 '25 05:10

Sandeep


1 Answers

Bash regexes can be tricky with quoting: regex metachars must NOT be quoted, but, since whitespace is significant in the shell, spaces must be quoted. This regex matching a string beginning and ending with a space:

[[ $s =~ ^" ".*" "$ ]] && echo y

To test if a string contains a space, do one of:

[[ $s =~ [[:space:]] ]] && echo y
[[ $s == *" "* ]] && echo y
like image 178
glenn jackman Avatar answered Oct 29 '25 18:10

glenn jackman