Bash – How to check if string contain alphabetic characters or alphabetic characters and numbers

bashregular expressionshell-script

I want to test STR contain alphabetic as (a-z) (A-Z) or alphabetic with numbers

meanwhile I have this

[[ "$STR"  =~ [a-zA-Z0-9] ]] && echo "contain alphanumerics"

but this works even STR have only numbers

while we want to print only if STR is contain alphabetic or alphabetic & numbers"

example

will print on the following case

gstfg523
HGFER34
JNF
GFGTVT
83bfF

will not print on

2424
4356
632
@65$
&%^$
82472243(*

Best Answer

Judging from the examples, I think you want to check that $STR is

  • fully alphanumeric (nothing but letters and numbers), and
  • not completely made of numbers (there is least one letter)?

Implementing those conditions:

[[ "$STR" =~ ^[[:alnum:]]*$ ]] && [[ ! "$STR" =~ ^[[:digit:]]+$ ]] && echo ok

This will also accept the empty string. To change that, use + instead of * in the first pattern.

Tests:

$ for STR in "" . .x .9 x x9 9 ; do 
    echo -en "$STR\t"; 
    [[ "$STR" =~ ^[[:alnum:]]*$ ]] && [[ ! "$STR" =~ ^[[:digit:]]+$ ]] && echo ok || echo not ok ; 
  done 
        ok
.       not ok
.x      not ok
.9      not ok
x       ok
x9      ok
9       not ok
Related Question