3

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(*
  • alphanumeric is letters and numbers. If your string has to check both, check for letters and then check for numbers (or reverse order). – ivanivan Jan 10 '18 at 15:10
  • ok my target is to check alphanomeic but it will not print if str is only numbers – jango Jan 10 '18 at 15:13
  • So, $STR must be fully alphanumeric (nothing but letters and numbers), and not completely made of numbers (at least one letter)? – ilkkachu Jan 10 '18 at 15:25
  • @jango, is your string always comprised of multiline text? – RomanPerekhrest Jan 10 '18 at 15:33
4

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
5

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"
2

If it is alphanumeric and not only numbers:

[[ "$STR"  =~ ^[a-zA-Z0-9]+$ ]] && [[ ! "$STR"  =~ ^[0-9]+$ ]] && echo …
  • why it print also in case - STR=Jkk@@ – jango Jan 10 '18 at 15:28
  • can you update the answer - if we want only alphabet or alphabet with numbers? – jango Jan 10 '18 at 15:29
  • @jango Answer updated. – Isaac Jan 10 '18 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.