Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash get a regular expression number up to 2 digits

Tags:

regex

bash

digit

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
like image 651
Bluz Avatar asked Nov 08 '13 16:11

Bluz


1 Answers

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))
like image 78
iruvar Avatar answered Nov 05 '22 01:11

iruvar