Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

alpha-numeric check

Status
Not open for further replies.

pjb

Programmer
May 1, 2001
148
US
What is a good way to check that a single character is not numeric and not an upper or lower case alpha?
 
Hi:

Just a couple of ksh ideas:

# is_digit: This function matches an all digits regular expression
# against an argument and returns 1 if the argument is digits else 0
# if isn't.
# Note the use of nawk. Use gawk for the Bash shell.
function is_digit
{
echo $1|nawk ' { if ($0 ~ /^[0-9]+$/)
print 1
else
print 0 } '
} # end is_digit

num="345"
ret_val=$(is_digit $num)
echo $ret_val


# downshift: this function return the argument as downshifted string
# usage: cmmd=$(down_shift $cmmd)
function down_shift {

# alternate translate command
#echo $1 | tr "[:upper:]" "[:lower:]"
echo $1 | tr '[A-Z]' '[a-z]'
} # end down_shift

string="ALLLOWERCASE"
string=$(down_shift $string)
printf "%s\n" $string

Regards,

Ed
Schaefer
 
Hi,

you can also use 'expr'
for example :

num=123
if expr "0$num" : "0[0-9]\+$" > /dev/null
then echo "Good"
else echo "Not numeric"
fi
Jean Pierre.
 
Okay, I understand the numeric part, but what about the alpha. I am working with a single character. The tr command will translate from lower to uper, but how do I tell if the result is from A to Z? The test command does not seem to allow an alpha operator when doing a less or greater comparison.
 
Assuming you pass in one character try sed

isAlphaNum ()
{
sed '
/[0-9a-zA-Z]/ {
s//T/
t
}
/./ s//F/
'
}

echo "@" | isAlphaNum # F
echo "a" | isAlphaNum # T

or do it in c:

#include <stdio.h>
#include <stdlib.h>

main()
{
int i;
i = (int)getchar();
printf(&quot;%s\n&quot;, (( i > 47 && i < 58 ) ||
( i > 64 && i < 91 ) ||
( i > 96 && i < 123 )) ? &quot;T&quot; : &quot;F&quot; );
exit(EXIT_SUCCESS);
}

and use the compiled program as you would the shell function.

Cheers,
ND
 



a=`echo $char | egrep &quot;[0-9a-zA-Z]&quot;`

if [ $a = $char ]
then
echo &quot;AplhaNumeric character&quot;
else
echo &quot;Non Alpha, Non Digit&quot;
fi




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top