Bash regex with hyphen and dot

岁酱吖の 提交于 2021-02-10 12:23:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!