How to check if string contain alphabetic characters or alphabetic characters and numbers?

19,429

Solution 1

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

Solution 2

For alnums with at least one alpha, that would be:

[[ $STR =~ ^[[:alnum:]]*[[:alpha:]][[:alnum:]]*$ ]]

(note that contrary to @ilkkachu's answer, that also excludes the empty string).

Or POSIXly:

valid() case $1 in
  (*[![:alnum:]]*) false;;
  (*[[:alpha:]]*) true;;
  (*) false;;
esac

valid "$STR" || printf >&2 '"%s" is not valid\n' "$STR"

Solution 3

If it is alphanumeric and not only numbers:

[[ "$STR"  =~ ^[a-zA-Z0-9]+$ ]] && [[ ! "$STR"  =~ ^[0-9]+$ ]] && echo …
Share:
19,429

Related videos on Youtube

jango
Author by

jango

Updated on September 18, 2022

Comments

  • jango
    jango over 1 year

    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(*
    
    • ivanivan
      ivanivan over 6 years
      alphanumeric is letters and numbers. If your string has to check both, check for letters and then check for numbers (or reverse order).
    • jango
      jango over 6 years
      ok my target is to check alphanomeic but it will not print if str is only numbers
    • ilkkachu
      ilkkachu over 6 years
      So, $STR must be fully alphanumeric (nothing but letters and numbers), and not completely made of numbers (at least one letter)?
    • RomanPerekhrest
      RomanPerekhrest over 6 years
      @jango, is your string always comprised of multiline text?
  • jango
    jango over 6 years
    why it print also in case - STR=Jkk@@
  • jango
    jango over 6 years
    can you update the answer - if we want only alphabet or alphabet with numbers?
  • done
    done over 6 years
    @jango Answer updated.