Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regex with hyphen and dot

Tags:

regex

bash

shell

I'm trying to match hostname with regex. For some reason the following code fails.

#!/bin/bash 
CONFIGURATION=m1si-ngxi-ddb01

#check configuration format
TMP_CONFIGURATION=",${CONFIGURATION}"
re=',[a-zA-Z0-9\-_\.]+'
if ! [[ $TMP_CONFIGURATION =~ $re ]]
then
        echo "configuration parttern mismatch."
        exit 1
fi

Testing:

[oracle@m1s-nyyy-db01 nir]$ vi a.sh
[oracle@m1s-nyyy-db01 nir]$
like image 323
Nir Avatar asked Feb 07 '26 01:02

Nir


1 Answers

The pattern you have is failing due to "escaped" chars and the fact that - is not at the end/start of the bracket expression. The \ is always treated as a literal backslash inside bracket expressions, they do not form any escape sequences. The hyphen is tricky, see the 9.3.5 RE Bracket Expression, Point 7:

The <hyphen-minus> character shall be treated as itself if it occurs first (after an initial '^', if any) or last in the list, or as an ending range point in a range expression.

Use

CONFIGURATION=m1si-ngxi-ddb01
#check configuration format
TMP_CONFIGURATION=",$CONFIGURATION"
re=',[a-zA-Z0-9_.-]+'
if ! [[ $TMP_CONFIGURATION =~ $re ]]
then
        echo "configuration parttern mismatch."
        exit 1
fi

See the online demo. Note that there is no need to put CONFIGURATION inside curly braces, $CONFIGURATION = ${CONFIGURATION}.

like image 195
Wiktor Stribiżew Avatar answered Feb 12 '26 05:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!