问题
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]$
回答1:
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}
.
来源:https://stackoverflow.com/questions/55377810/bash-regex-with-hyphen-and-dot