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

Share:
16,252
kheraud
Author by

kheraud

Programming in Go, Scala, Python, Java, Bash... Focusing mostly on devops approaches and engineering matters.

Updated on June 08, 2022

Comments

  • kheraud
    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
      Chris Eberle almost 13 years
      Generally in bash you'll want to rely pretty heavily on grep or awk to do any pattern matching.
  • Gordon Davisson
    Gordon Davisson almost 13 years
    Several 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
    Martin almost 13 years
    Thank you for correcting the syntax. Updated as to not confuse.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Be careful with this one. $ [[ "一" =~ ^[[:alnum:]]*$ ]] ; echo $? 0
  • Gordon Davisson
    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
    Ignacio Vazquez-Abrams almost 13 years
    If your bash uses Unicode classes then it will be true, as is "1" in Japanese.