regexbashdigit

bash get a regular expression number up to 2 digits


I simply need to know how to make a regex that accepts a number that has up to 2 digits

All I have just now is

^[0-9]{2}$

Which would match a number with exactly 2 digits, but I don't know how to specify "match a number which has up to 2 digits".

Also, if there is a way to make sure that this number isn't 0 then that would be a plus, otherwise I can check that with Bash.

Thanks ! :)

Note that the input variable comes from read -p "make a choice" Number

EDITING MY POST - SHOWING CODE IN CONTEXT :

while true; do
    read -p "Please key in the number of the engineer of your choice, or leave empty to select them all: " Engineer
    if [ -z "$Engineer" ]; then
        echo "No particular user specified, all engineers will be selected."
        UserIdSqlString="Transactions.Creator!=0 "
        break
    else
        if [[ $Engineer =~ ^[0-9]{1,2}$ && $Engineer -ne 0 ]]; then
            echo "If you want a specific engineer type their number otherwise leave blank"  
        else
            echo "yes"
            break
        fi
    fi
done

Solution

  • the bash [[ conditional expression supports extended regular expressions.

    [[ $number =~ ^[0-9]{,2}$ && $number -ne 0 ]]
    

    or as the inimitable @gniourf_gniourf points out in his comments, the following is needed to handle numbers with leading zeroes correctly

    [[ $number =~ ^[0-9]{,2}$ ]] && ((number=10#$number))