How to check if a string only contains A-Z, a-z and 0-9?
16,252
Solution 1
$ [[ "foo" =~ ^[A-Za-z0-9]*$ ]] ; echo $?
0
$ [[ "foo " =~ ^[A-Za-z0-9]*$ ]] ; echo $?
1
Solution 2
if `echo $VARIABLE | egrep '[^A-Za-z0-9]'`; then echo VARIABLE IS BAD; fi
A pure shell option
case "$VARAIBLE" in *[^A-Za-z0-9]*) echo VARIABLE IS BAD;; esac
Solution 3
if [[ "$VARIABLE" =~ ^[[:alnum:]]*$ ]]; then do something; fi;
useful resources: http://bashshell.net/regular-expressions/ , http://www.gnu.org/software/bash/manual/bashref.html
Author by
kheraud
Programming in Go, Scala, Python, Java, Bash... Focusing mostly on devops approaches and engineering matters.
Updated on June 08, 2022Comments
-
kheraud almost 2 years
What is the best way to validate a string with a pattern? I would use PCRE but I don't know if it is embedded in each shell and how to use it.
For example, how could I validate that variable only contains A-Z, a-Z and 0-9 and does not contain spaces, ', ", ... ?
-
Chris Eberle almost 13 yearsGenerally in bash you'll want to rely pretty heavily on
grep
orawk
to do any pattern matching.
-
-
Gordon Davisson almost 13 yearsSeveral corrections: there cannot be spaces between the outer double-brackets, the
[:alnum:]
needs another set of brackets, and should be followed by*
to let it match more than one character. Fixed version:if [[ "$VARIABLE" =~ ^[[:alnum:]]*$ ]]; then do something; fi
-
Martin almost 13 yearsThank you for correcting the syntax. Updated as to not confuse.
-
Ignacio Vazquez-Abrams almost 13 yearsBe careful with this one.
$ [[ "一" =~ ^[[:alnum:]]*$ ]] ; echo $?
0
-
Gordon Davisson almost 13 years@Ignacio: that prints 1 for me (as expected). Is
一
in the alnum character class in some other locale (I'm using LANG=en_US.UTF-8)? -
Ignacio Vazquez-Abrams almost 13 yearsIf your bash uses Unicode classes then it will be true, as
一
is "1" in Japanese.