Steven Yang
Steven Yang

Reputation: 23

regex of numbers

I am writing in bash, this script is supposed to output 'success', but it did not. Is the regex for numbers wrong?

var=5
if [[ "$var" =~ ^[:digit:]$ ]]; then 
    echo success
fi

Thnx!

Upvotes: 2

Views: 61

Answers (2)

heemayl
heemayl

Reputation: 42007

You need to put the character class [:digit:] inside bracket expression []:

[[ "$var" =~ ^[[:digit:]]$ ]]

In ASCII locale, this is necessarily equivalent to:

[[ "$var" =~ ^[0-9]$ ]]

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

You will need to put [:digit:] inside a character class:

var=5
if [[ "$var" =~ ^[[:digit:]]$ ]]; then 
    echo success
fi

Also note that if you want to match multi digit numbers (> 9) you will need to use the plus metacharacter (+):

if [[ "$var" =~ ^[[:digit:]]+$ ]]; then 
    echo success
fi

Upvotes: 2

Related Questions