1847087 Members
5590 Online
110262 Solutions
New Discussion

check string feature

 
SOLVED
Go to solution
SILVERSTAR
Frequent Advisor

check string feature

Hi ,

I need to check that a variable read by a posix shell script is as follows
length 8,
first 5 digits are alfanumeric
last 3 digits are numeric

any help apprciated.
Thanks
Angelo
4 REPLIES 4
Jeff_Traigle
Honored Contributor
Solution

Re: check string feature

There may be a more condensed syntax for this, but this works:

case ${VARIABLE} in
[a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][0-9][0-9][0-9]) echo "Good value" ;;
*) echo "Bad value" ;;
esac
--
Jeff Traigle
A. Clay Stephenson
Acclaimed Contributor

Re: check string feature


When can leverage the enhanced grep command to match an anchored string.

checkvar()
{
typeset -i GSTAT=2
if [[ ${#} -eq 1 ]]
then
typeset X=${1}
shift
echo "${X}" | grep -E -q -e '^[A-Za-z0-9]{5}[0-9]{3}$'
GSTAT=${?}
fi
return ${GSTAT}
} # checkvar


read MYVAR
checkvar ${MYVAR}
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then
echo "Ok"
else
echo "Bad format"
fi

Man grep for details.
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: check string feature


Similar in perl:

perl -e 'exit (@ARGV[0] =~ /^[A-Za-z0-9]{5}\d{3}$/)' $your_variable

This sets $? to 1 on match, 0 else.

Are you sure you mean Alphanumeric in those first 5, or perhaps just Alpha
Alpha: [A-Za-z]
AlphaNumeric: [A-Za-z0-9]

And if alpha-numeric, with "_" is allowed then you can use \w in perl:

perl -e 'exit (@ARGV[0] =~ /^\w{5}\d{3}$/)' $your_variable


fwiw,
Hein.
SILVERSTAR
Frequent Advisor

Re: check string feature

well done